递归加移位思想,困住我的竟然是边界溢出值,要哭了:
class Solution {
private:
int function(long num, long divisor) {
if (num<divisor)
return 0;
long long time = 1;
long long temp = divisor;
while (num >= temp) {
temp = temp << 1;
time = time << 1;
}
time = time >> 1;
return time + function(num - (temp >> 1), divisor);
}
public:
int divide(long dividend, long divisor) {
if(divisor == 1) return dividend;
if(divisor == -1){
if(dividend>INT_MIN) return -dividend;
return INT_MAX;
}
static_cast<long>(dividend);
static_cast<long>(divisor);
bool div1 = false, div2 = false;
if (dividend<0) {
dividend = -dividend;
div1 = true;
}
if (divisor<0) {
divisor = -divisor;
div2 = true;
}
if (div1 == div2)
return function(dividend, divisor);
else
return -function(dividend, divisor);
}
};