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