Java

问题

解决int相加后怎么判断是否溢出,如果溢出就返回Integer.MAX_VALUE

解决方案

JDK8已经实现了在Math包下

加法

  1. public static int addExact(int x, int y) {
  2. int r = x + y;
  3. // HD 2-12 Overflow iff both arguments have the opposite sign of the result
  4. if (((x ^ r) & (y ^ r)) < 0) {
  5. throw new ArithmeticException("integer overflow");
  6. }
  7. return r;
  8. }

减法

  1. public static int subtractExact(int x, int y) {
  2. int r = x - y;
  3. // HD 2-12 Overflow iff the arguments have different signs and
  4. // the sign of the result is different than the sign of x
  5. if (((x ^ y) & (x ^ r)) < 0) {
  6. throw new ArithmeticException("integer overflow");
  7. }
  8. return r;
  9. }

乘法

  1. public static int multiplyExact(int x, int y) {
  2. long r = (long)x * (long)y;
  3. if ((int)r != r) {
  4. throw new ArithmeticException("integer overflow");
  5. }
  6. return (int)r;
  7. }

注意 long和int是不一样的

  1. public static long multiplyExact(long x, long y) {
  2. long r = x * y;
  3. long ax = Math.abs(x);
  4. long ay = Math.abs(y);
  5. if (((ax | ay) >>> 31 != 0)) {
  6. // Some bits greater than 2^31 that might cause overflow
  7. // Check the result using the divide operator
  8. // and check for the special case of Long.MIN_VALUE * -1
  9. if (((y != 0) && (r / y != x)) ||
  10. (x == Long.MIN_VALUE && y == -1)) {
  11. throw new ArithmeticException("long overflow");
  12. }
  13. }
  14. return r;
  15. }