Adding/subtracting 两个数字字符串
Adding/subtracting two numeric strings
我有两个大数字设置为字符串的变量:
var numA = "340282366920938463463374607431768211456"
var numB = "17014118346046923173168730371588410572"
我希望能够在 Go 中对这些大字符串数字进行加减运算。
我知道我需要使用 math/big
但我仍然无法弄清楚如何使用,所以任何示例帮助将不胜感激!
您可以使用 big.NewInt()
to create a new big.Int
value initialized with an int64
value. It returns you a pointer (*big.Int
). Alternatively you could simply use the builtin new()
function to allocate a big.Int
value which will be 0
like this: new(big.Int)
, or since big.Int
is a struct type, a simple composite literal 也可以:&big.Int{}
.
一旦你有了一个值,你就可以使用Int.SetString()
来解析并设置一个给定的数字string
。您可以传递字符串数字的基数,它还会 returns 您一个 bool
值,指示解析是否成功。
那么你可以用Int.Add()
and Int.Sub()
计算2个big.Int
数的和与差。注意 Add()
和 Sub()
将结果写入您调用其方法的接收器,因此如果您需要数字(操作数)不变,请使用另一个 big.Int
值来计算和存储结果。
看这个例子:
numA := "340282366920938463463374607431768211456"
numB := "17014118346046923173168730371588410572"
ba, bb := big.NewInt(0), big.NewInt(0)
if _, ok := ba.SetString(numA, 10); !ok {
panic("invalid numA")
}
if _, ok := bb.SetString(numB, 10); !ok {
panic("invalid numB")
}
sum := big.NewInt(0).Add(ba, bb)
fmt.Println("a + b =", sum)
diff := big.NewInt(0).Sub(ba, bb)
fmt.Println("a - b =", diff)
输出(在 Go Playground 上尝试):
a + b = 357296485266985386636543337803356622028
a - b = 323268248574891540290205877060179800884
我有两个大数字设置为字符串的变量:
var numA = "340282366920938463463374607431768211456"
var numB = "17014118346046923173168730371588410572"
我希望能够在 Go 中对这些大字符串数字进行加减运算。
我知道我需要使用 math/big
但我仍然无法弄清楚如何使用,所以任何示例帮助将不胜感激!
您可以使用 big.NewInt()
to create a new big.Int
value initialized with an int64
value. It returns you a pointer (*big.Int
). Alternatively you could simply use the builtin new()
function to allocate a big.Int
value which will be 0
like this: new(big.Int)
, or since big.Int
is a struct type, a simple composite literal 也可以:&big.Int{}
.
一旦你有了一个值,你就可以使用Int.SetString()
来解析并设置一个给定的数字string
。您可以传递字符串数字的基数,它还会 returns 您一个 bool
值,指示解析是否成功。
那么你可以用Int.Add()
and Int.Sub()
计算2个big.Int
数的和与差。注意 Add()
和 Sub()
将结果写入您调用其方法的接收器,因此如果您需要数字(操作数)不变,请使用另一个 big.Int
值来计算和存储结果。
看这个例子:
numA := "340282366920938463463374607431768211456"
numB := "17014118346046923173168730371588410572"
ba, bb := big.NewInt(0), big.NewInt(0)
if _, ok := ba.SetString(numA, 10); !ok {
panic("invalid numA")
}
if _, ok := bb.SetString(numB, 10); !ok {
panic("invalid numB")
}
sum := big.NewInt(0).Add(ba, bb)
fmt.Println("a + b =", sum)
diff := big.NewInt(0).Sub(ba, bb)
fmt.Println("a - b =", diff)
输出(在 Go Playground 上尝试):
a + b = 357296485266985386636543337803356622028
a - b = 323268248574891540290205877060179800884