問題描述
我知道這樣的話題被問了好幾次,但我的問題是關于完整的 32 位 int 的溢出.例如:
I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:
11111111111111111111111111111111 +
00000000000000000000000000000001 =
00000000000000000000000000000000 //overflow!
我發(fā)現(xiàn) topic 有類似的問題,但是算法并不完美.
I found topic with similar question about this, however the algorithm is not perfect.
11111111111111111111111111111111 +
00000000000000000000000000000000 =
00000000000000000000000000000000 //overflow!
有沒有什么簡單、快速、安全的檢查方法?
Is there any simple, fast, safer way to check this ?
推薦答案
Math.addExact
溢出時拋出異常
從 Java 8 開始,數(shù)學
類:
Math.addExact
throws exception on overflow
Since Java 8 there is a set of methods in the Math
class:
toIntExact(long)
addExact(int,int)
subtractExact(int,int)
multiplyExact(int,int)
……以及長期版本.
這些方法中的每一個都會拋出 ArithmeticException
如果發(fā)生溢出.否則,如果它在范圍內(nèi),它們會返回正確的結果.
Each of these methods throws ArithmeticException
if overflow happens. Otherwise they return the proper result if it fits within the range.
加法示例:
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 上實時運行的代碼.
對不起,java.lang.ArithmeticException:整數(shù)溢出
Sorry, java.lang.ArithmeticException: integer overflow
這篇關于如何檢測 32 位 int 上的整數(shù)溢出?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!