Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
1 - 细节实现题。题目要求不使用乘法、除法和取模,还么还可以使用加法,减法和位运算。
2 - 最简单的方法,是不断减去被除数。
3 - 在这个基础上,可以做一点优化,每次把被除数翻倍,从而加速。
class Solution {
public:
int divide(int dividend, int divisor) {
//INT_MIN/-1会溢出,因此使用unsigned int
unsigned int result = 0;
int sign = (dividend>0 ^ divisor>0);
unsigned int a = abs(dividend);
unsigned int b = abs(divisor);
while(a>=b){
long long temp = b;
int i = 0;
//为提高效率,可让除数每次翻倍
for(;temp<=a;i++){
temp = temp << 1;
}
//用被除数减去除数,以确定倍数
a -= b << (i-1);
result += 1 << (i-1);
}
return sign ? -result : (result<=INT_MAX ? result : INT_MAX);
}
};