本文共 1477 字,大约阅读时间需要 4 分钟。
????????????????????????????????????????????????
public static int addExact(int x, int y) { int r = x + y; // ??????? boolean overflow = ( (x ^ r) > 0 ) != ( (y ^ r) > 0 ); if (overflow) { throw new ArithmeticException("integer overflow"); } return r;}
public static int subtractExact(int x, int y) { int r = x - y; // ??????? boolean overflow = ( (x ^ r) > 0 ) != ( (y ^ r) > 0 ); if (overflow) { 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; // ??????? if ( (x == 0 || y == 0) ) { return r; } // ??????? long ax = Math.abs(x); long ay = Math.abs(y); if ( (ax > Integer.MAX_VALUE / ay) || (ay > Integer.MAX_VALUE / ax) ) { // ???? long temp = r / y; if ( (y != 0) && (temp != x) ) { throw new ArithmeticException("long overflow"); } // ?????? if (x == Long.MIN_VALUE && y == -1) { throw new ArithmeticException("long overflow"); } } return r;}
?????????x?y???r?????????????????????????????
???????????????????????
??????????????????????????????
?????????????????????????Long.MIN_VALUE?-1????
??????????????????????????????????????
转载地址:http://trch.baihongyu.com/