【问题标题】:Integer.MIN_VALUE divide by -1Integer.MIN_VALUE 除以 -1
【发布时间】:2018-08-21 16:39:06
【问题描述】:

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

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

问题:

不使用乘法、除法和取模运算符将两个整数相除。

如果溢出,返回2147483647

回答

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;
}

【问题讨论】:

    标签: java integer-overflow


    【解决方案1】:

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

    • Integer.MAX_VALUE2147483647
    • Integer.MIN_VALUE-2147483648

    如果您将Integer.MIN_VALUE 除以-1,则值会溢出(2147483648 &gt; 2147483647),因此此操作必须有限制。

    【讨论】:

      【解决方案2】:

      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)。

      【讨论】:

        猜你喜欢
        • 2012-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        • 2015-11-03
        • 2023-03-21
        • 2011-07-23
        • 1970-01-01
        相关资源
        最近更新 更多