整数相加溢出
一,问题描述
java开发中,经常遇到整数处理,整数的存储是有范围的,Integer.MAX_VALUE = 21亿多
二,问题处理
jdk1.8已经有处理方法了 。实际使用过程也可以自己写util类,重写异常处理,而不是抛ari异常
加法 public static int addExact(int x, int y) { int r = x + y; if (((x ^ r) & (y ^ r)) < 0) { throw new ArithmeticException("integer overflow"); } return r; }
减法 public static int subtractExact(int x, int y) { int r = x - y; if (((x ^ y) & (x ^ r)) < 0) { throw new ArithmeticException("integer overflow"); } return r; }
乘法 public static int multiplyExact(int x, int y) { long r = (long)x * (long)y; if ((int)r != r) { throw new ArithmeticException("integer overflow"); } return (int)r; }
三,总结
public static long multiplyExact(long x, long y) { long r = x * y; long ax = Math.abs(x); long ay = Math.abs(y); if (((ax | ay) >>> 31 != 0)) { if (((y != 0) && (r / y != x)) || (x == Long.MIN_VALUE && y == -1)) { throw new ArithmeticException("long overflow"); } } return r; }
long和int是有区别的。
更多方法,可以查查jdk的Maht方法。提升自我