douchen2025 2018-06-07 15:10
浏览 58
已采纳

测试整数乘法的溢出

Overflows don't seem to be part of the builtin packages in go.

What is the best way to test that you don't overflow when multiplying 2 integers ?

Something similar to Java Math.multiplyExact ...

  • 写回答

1条回答 默认 最新

  • duanlu7680 2018-06-07 15:15
    关注

    It'd be possible for you to write your own multiplyExact based on the suggestions on this thread:

    https://groups.google.com/forum/#!msg/golang-nuts/h5oSN5t3Au4/KaNQREhZh0QJ

    const mostNegative = -(mostPositive + 1)
    const mostPositive = 1<<63 - 1
    
    func multiplyExact(a, b int64) (int64, error) {
        result := a * b
        if a == 0 || b == 0 || a == 1 || b == 1 {
            return result, nil
        }
        if a == mostNegative || b == mostNegative {
            return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
        }
        if result/b != a {
            return result, fmt.Errorf("Overflow multiplying %v and %v", a, b)
        }
        return result, nil
    }
    

    Playground: https://play.golang.org/p/V_TSC44VcPY

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站