1 题目
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
2 解法
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor == 0 || dividend == Integer.MIN_VALUE && divisor == -1){
return Integer.MAX_VALUE;
}
int res = 0;
int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1;
long ldividend = Math.abs((long)dividend);
long ldivisor = Math.abs((long)divisor);
while(ldividend >= ldivisor){
int count = 1;
long temp = ldivisor;
while((temp<<1) <= ldividend){
count <<= 1;
temp <<= 1;
}
ldividend -= temp;
res += count;
}
return sign < 0 ? -res : res;
}
}