dongzeao5047 2018-07-05 06:43
浏览 116
已采纳

加/减两个数字字符串

I have two variables with big numbers set as strings:

var numA = "340282366920938463463374607431768211456"
var numB = "17014118346046923173168730371588410572"

I want to be able to add and subtract these kinds of large string numbers in Go.

I know I need to use math/big but I still can not for the life of me figure out how, so any example help will be greatly appreciated!

  • 写回答

1条回答 默认 最新

  • duankang8114 2018-07-05 06:57
    关注

    You may use 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 would also do: &big.Int{}.

    Once you have a value, you may use Int.SetString() to parse and set a number given as string. You can pass the base of the string number, and it also returns you a bool value indicating if parsing succeeded.

    Then you may use Int.Add() and Int.Sub() to calculate the sum and difference of 2 big.Int numbers. Note that Add() and Sub() write the result into the receiver whose method you call, so if you need the numbers (operands) unchanged, use another big.Int value to calculate and store the result.

    See this example:

    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)
    

    Output (try it on the Go Playground):

    a + b = 357296485266985386636543337803356622028
    a - b = 323268248574891540290205877060179800884
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败