Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

If it is overflow, return 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;
}
like image 659
Gauge Wang Avatar asked Aug 21 '18 16:08

Gauge Wang


People also ask

What does integer MIN_VALUE do?

The Integer. MIN_VALUE is a constant in the Integer class that represents the minimum or least integer value that can be represented in 32 bits, which is -2147483648, -231. This is the lowest value that any integer variable in Java can hold.

What is number MIN_VALUE in Javascript?

Number. MIN_VALUE is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0.

What is 5e 324?

MIN_VALUE is 5e-324 , i.e. the smallest positive number that can be represented within float precision, i.e. that's as close as you can get to zero. It defines the best resolution floats give you. Now the overall smallest value is Number.


2 Answers

Because, the absolute values of Integer.MAX_VALUE and Integer.MIN_VALUE are not equal.

  • Integer.MAX_VALUE is 2147483647
  • Integer.MIN_VALUE is -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.

like image 195
Nikolas Charalambidis Avatar answered Nov 12 '22 17:11

Nikolas Charalambidis


Java use 32 bit to store int.

The max int value is 231-1

0111 1111 1111 1111 1111 1111 1111 1111

The min int value is -231

1000 0000 0000 0000 0000 0000 0000 0000

In other words, int does not have a big enough value to store 231(-Integer.MIN_VALUE).

like image 25
xingbin Avatar answered Nov 12 '22 15:11

xingbin