Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路:注意使用long进行计算,防止int溢出,然后再判断溢出时重置。
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor == 0){
return 0;
}
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
long res = 0;
boolean isPositive = ((dividend ^ divisor) >> 31) == 0;
while (a >= b) {
long c = b;
for (long i = 0; a >= c; i++, c <<= 1) {
a -= c;
res += 1 << i;
if ((isPositive && res > Integer.MAX_VALUE) || (!isPositive && -res < Integer.MIN_VALUE)) {
return Integer.MAX_VALUE;
}
}
}
return isPositive ? (int) res : (int) -res;
}
}