if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return 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;
}
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.
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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With