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;
}
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 2 31 -1
0111 1111 1111 1111 1111 1111 1111 1111
The min int value is -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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.