如何检测 32 位 int 上的整数溢出?

我知道这样的话题被问了好几次,但我的问题是关于完整的 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!

我发现 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 开始,数学类:

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.

加法示例:

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:整数溢出

Sorry, java.lang.ArithmeticException: integer overflow

相关文章