题目:
Divide two integers without using multiplication, division and mod operator.
class Solution {
public:
int divide(int dividend, int divisor) {
int flag = 1;
//判断符号
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
flag = -1;
int ans;
long long m = abs((long long)dividend);
long long n = abs((long long)divisor);
long long beg = 0, end = m;
long long mid;
long long tmp;
while (beg <= end) {
mid = (beg + end) >> 1;
tmp = mul(mid, n);
if (tmp == m) {
ans = mid;
break;
}
else if (tmp > m)
end = mid - 1;
else {
ans = mid;
beg = mid + 1;
}
}
return flag < 0 ? -ans : ans;
}
//实现mid*divisor
long long mul(long long mid, long long divisor) {
if (mid == 0)
return 0;
long long tmp = mul(mid >> 1, divisor) << 1;
//若为奇数,结果加上一个divisor
if (mid & 1)
tmp += divisor;
return tmp;
}
};