Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
public class Solution {
public int divide (int dividend, int divisor) {
final int MAX = 0x7fffffff, MIN = 0x80000000;
if (divisor == 0 || (divisor == -1 && dividend == MIN))
return MAX;
int sign = (dividend >= 0 && divisor > 0 || dividend <=0 && divisor < 0) ? 1 : -1;
dividend = dividend > 0 ? -dividend : dividend;
divisor = divisor > 0 ? -divisor : divisor;
if (dividend > divisor)
return 0;
if (divisor == -1)
return sign == 1 ? -dividend : dividend;
//前面都是对部分简单情况进行判断
int res = 0;
while (dividend <= divisor) {
int divisorCurrent = divisor;
int resCurrent = 1;
while (divisorCurrent > dividend >> 1) {//除数是否大于被除数的二分之一
divisorCurrent = divisorCurrent << 1;
resCurrent = resCurrent << 1;
//结果和除数分别扩大一倍
}
res += resCurrent;
dividend -= divisorCurrent;
//结果添加好之后,继续进行下一轮计算
}
return sign == 1 ? res : -res;
}
}