問題描述
我知道這樣的話題被問了好幾次,但我的問題是關(guān)于完整的 32 位 int 的溢出.例如:
I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:
我發(fā)現(xiàn) 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
溢出時(shí)拋出異常
從 Java 8 開始,數(shù)學(xué)
類:
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)
……以及長期版本.
這些方法中的每一個(gè)都會(huì)拋出 ArithmeticException
如果發(fā)生溢出.否則,如果它在范圍內(nèi),它們會(huì)返回正確的結(jié)果.
Each of these methods throws ArithmeticException
if overflow happens. Otherwise they return the proper result if it fits within the range.
加法示例:
查看此在 IdeOne.com 上實(shí)時(shí)運(yùn)行的代碼.
對不起,java.lang.ArithmeticException:整數(shù)溢出
Sorry, java.lang.ArithmeticException: integer overflow
這篇關(guān)于如何檢測 32 位 int 上的整數(shù)溢出?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!