简体   繁体   English

Integer.MIN_VALUE除以-1

[英]Integer.MIN_VALUE divide by -1

why this line of code matters?(I get a wrong answer without it) 为什么这行代码很重要?(没有它我会得到一个错误的答案)

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

The question: 问题:

Divide two integers without using multiplication, division and mod operator. 在不使用乘法,除法和mod运算符的情况下除以两个整数。

If it is overflow, return 2147483647 如果溢出,则返回2147483647

Answer 回答

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

Because, the absolute values of Integer.MAX_VALUE and Integer.MIN_VALUE are not equal. 因为, Integer.MAX_VALUEInteger.MIN_VALUE的绝对值不相等。

  • Integer.MAX_VALUE is 2147483647 Integer.MAX_VALUE2147483647
  • Integer.MIN_VALUE is -2147483648 Integer.MIN_VALUE-2147483648

In case you divide Integer.MIN_VALUE by -1 , the value would overflow ( 2147483648 > 2147483647 ), thus there must be a limit for this operation. 如果将Integer.MIN_VALUE除以-1 ,则该值将溢出( 2147483648 > 2147483647 ),因此必须对此操作进行限制。

Java use 32 bit to store int . Java使用32位来存储int

The max int value is 2 31 -1 max int值为2 31 -1

0111 1111 1111 1111 1111 1111 1111 1111

The min int value is -2 31 min int值为-2 31

1000 0000 0000 0000 0000 0000 0000 0000

In other words, int does not have a big enough value to store 2 31 ( -Integer.MIN_VALUE ). 换句话说,int没有足够大的值来存储2 31-Integer.MIN_VALUE )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM