通过右移’>>’操作使除数乘2,在logN的时间内得到2^p
class Solution { //不断右移扩大除数,在O(logN)完成除法(注意边界INT_MAX/INT_MIN,右移越界导致死循环,用long long防止越界)
public:
int divide(int dividend, int divisor) {
if (dividend == INT_MIN && divisor == -1)
return INT_MAX;
long long abs_dividend = abs((long long)dividend), abs_divisor = abs((long long)divisor), result = 0;
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
if (abs_divisor == 1)
return sign == 1 ? abs_dividend : -abs_dividend;
if (abs_dividend < abs_divisor)
return 0;
long long total = abs_divisor, time = 1;
while (abs_dividend - total >= total)
{
time <<= 1;
total <<= 1;
}
result += time;
abs_dividend -= total;
while (time && abs_dividend >= abs_divisor)
{
if (abs_dividend - total > 0)
{
abs_dividend -= total;
result += time;
}
total >>= 1;
time >>= 1;
}
return sign > 0 ? result : -result;
}
};