我知道这个话题已经被问过好几次了,但是我的问题是关于完整 32 位 int 的溢出。例如:
11111111111111111111111111111111 +
00000000000000000000000000000001 =
00000000000000000000000000000000 //overflow!
I found topic https://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c对此有类似的问题,但是该算法并不完美。
11111111111111111111111111111111 +
00000000000000000000000000000000 =
00000000000000000000000000000000 //overflow!
有没有简单、快速、安全的方法来检查呢?
Math.addExact
溢出时抛出异常
从 Java 8 开始,有一组方法Math https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html class:
- toIntExact(long) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#toIntExact(long)
- addExact(int,int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#addExact(int,int)
- subtractExact(int,int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#subtractExact(int,int)
- multiplyExact(int,int) https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#multiplyExact(int,int)
……还有很长的版本。
这些方法中的每一个都会抛出ArithmeticException https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ArithmeticException.html如果发生溢出。否则,如果结果在范围内,它们就会返回正确的结果。
添加示例:
int x = 2_000_000_000;
int y = 1_000_000_000;
try {
int result = Math.addExact(x, y);
System.out.println("The proper result is " + result);
} catch(ArithmeticException e) {
System.out.println("Sorry, " + e);
}
看到这个代码在 IdeOne.com 上实时运行 https://ideone.com/cAlYwX.
抱歉,java.lang.ArithmeticException:整数溢出
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)