题目
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路
这题是参考了leetcode上的solution。
这题比较重要的是long long的运用。因为不能使用乘法,除法和取余,所以使用位移。首先排除极端情况,除数为0或者是结果溢出。然后,通过不断位移来找到跟被除数最接近的小于它的除数的2倍数,然后用被除数减去该数来求出差值,循环往复,直到差值小于或者等于除数。
代码
class Solution {
public:
int divide(int dividend, int divisor) {
int sign = (dividend<0) ^ (divisor<0) ? -1:1;
if (divisor == 0 || (dividend == INT32_MIN && divisor == -1)) {
return INT32_MAX;
}
long long did = labs(dividend);
long long dis = labs(divisor);
int n = 0;
while (dis <= did) {
int multiple = 1;
long long tmp = dis;
while ((tmp << 1) <= did) {
tmp <<= 1;
multiple <<= 1;
}
did -= tmp;
n += multiple;
}
return sign == 1 ? n:-n;
}
};