Integer.MIN_VALUE 除以-1

Integer.MIN_VALUE divide by -1

为什么这行代码很重要?(没有它我会得到一个错误的答案)

if (dividend == Integer.MIN_VALUE && divisor == -1) {
    return Integer.MAX_VALUE;
}

问题:

不使用乘法、除法和 mod 运算符来除两个整数。

如果溢出,return2147483647

回答

public int divide(int dividend, int divisor) {

    if(divisor == 0){
        return dividend > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    }

    if(dividend == 0){
        return 0;
    }

    if (dividend == Integer.MIN_VALUE && divisor == -1) {
        return Integer.MAX_VALUE;
    }

    boolean isNeg = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);


    Long up = Math.abs((long) dividend);
    Long down = Math.abs((long) divisor);

    int res = 0;

    while(up >= down){
        int shift = 0;

        while(up >= (down << shift)){
            shift++;
        }

        up -= down << (shift - 1);
        res += 1 << (shift - 1);
    }

    return isNeg ? -res : res;
}

因为Integer.MAX_VALUEInteger.MIN_VALUE的绝对值不相等

  • Integer.MAX_VALUE2147483647
  • Integer.MIN_VALUE-2147483648

如果你用Integer.MIN_VALUE除以-1,这个值会溢出(2147483648 > 2147483647),因此这个操作必须有一个限制。

Java使用32位存储int.

最大int值为231-1

0111 1111 1111 1111 1111 1111 1111 1111

最小int值为-231

1000 0000 0000 0000 0000 0000 0000 0000

换句话说,int没有足够大的值来存储231(-Integer.MIN_VALUE).