LeetCode: divideInteger

时间:2021-04-19 16:51:56

Title:

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

思路就是每次以两倍增长除数,知道即将大于被除数,然后用被除数减去,在循环。

遇到int整数问题一定要考虑到INT_MAX和INT_MIN。

class Solution {
public:
int divide(int dividend, int divisor) {
int final = ;
/////// overflow///////
if (divisor == || (dividend == INT_MIN && divisor == -)){
return INT_MAX;
}
int nega = ;
if ((dividend>&&divisor<) || (dividend<&&divisor>))
nega = ;
//如果为INT_MIN则求abs为越界
long long a = abs((long long)dividend);
long long b = abs((long long)divisor);
if (b > a)
return ;
long long sum = ;//后面有sum += sum防止越界
int count = ;
while (a >= b)
{
count = ; //a >= b保证了最少有一个count
sum = b;
while (sum + sum <= a){
sum += sum;
count += count;
}
a -= sum;
final += count;
}
if (nega)
final = - final;
return final;
}
};