猿问
下载APP

如何检查Java中的两个数字是否会引起溢出?

我想处理将两个数字相乘会导致溢出的特殊情况。代码看起来像这样:


int a = 20;

long b = 30;


// if a or b are big enough, this result will silently overflow

long c = a * b;

那是一个简化的版本。在实际程序中,a并且b在运行时从其他地方获取。我想要实现的是这样的:


long c;

if (a * b will overflow) {

    c = Long.MAX_VALUE;

} else {

    c = a * b;

}

您如何建议我最好编写此代码?


更新:a和b总是非负在我的情况。


莫回无
浏览 308回答 3
3回答

波斯汪

Java的8有Math.multiplyExact,Math.addExact等,为整数且长。这些会引发未经检查ArithmeticException的溢出。

若吾皇

如果a和b均为正,则可以使用:if (a != 0 && b > Long.MAX_VALUE / a) {&nbsp; &nbsp; // Overflow}如果您需要同时处理正数和负数,则更加复杂:long maximum = Long.signum(a) == Long.signum(b) ? Long.MAX_VALUE : Long.MIN_VALUE;if (a != 0 && (b > 0 && b > maximum / a ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;b < 0 && b < maximum / a)){&nbsp; &nbsp; // Overflow}这是一张小桌子,我用鞭打检查一下,假装溢出发生在-10或+10:a =&nbsp; 5&nbsp; &nbsp;b =&nbsp; 2&nbsp; &nbsp; &nbsp;2 >&nbsp; 10 /&nbsp; 5a =&nbsp; 2&nbsp; &nbsp;b =&nbsp; 5&nbsp; &nbsp; &nbsp;5 >&nbsp; 10 /&nbsp; 2a = -5&nbsp; &nbsp;b =&nbsp; 2&nbsp; &nbsp; &nbsp;2 > -10 / -5a = -2&nbsp; &nbsp;b =&nbsp; 5&nbsp; &nbsp; &nbsp;5 > -10 / -2a =&nbsp; 5&nbsp; &nbsp;b = -2&nbsp; &nbsp; -2 < -10 /&nbsp; 5a =&nbsp; 2&nbsp; &nbsp;b = -5&nbsp; &nbsp; -5 < -10 /&nbsp; 2a = -5&nbsp; &nbsp;b = -2&nbsp; &nbsp; -2 <&nbsp; 10 / -5a = -2&nbsp; &nbsp;b = -5&nbsp; &nbsp; -5 <&nbsp; 10 / -2

收到一只叮咚

您可以改用java.math.BigInteger并检查结果的大小(尚未测试代码):BigInteger bigC = BigInteger.valueOf(a) * multiply(BigInteger.valueOf(b));if(bigC.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {&nbsp; c = Long.MAX_VALUE;} else {&nbsp; c = bigC.longValue()}
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答