29. Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
solutions:
本题意是给定两个整数除数和除数,不使用乘法、除法和模除以两个整数。除以除数后的商。整数除法应截断为零。
一开始我们可以很容易的想到使用减法,但是也很必然的超时错误。对其做优化,由于不能使用乘法,所以使用代替的位运算来进行优化。
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend == -2147483648 && divisor == -1)
return 2147483647;
long long a = abs((double)dividend);
long long b = abs((double)divisor);
int result = 0;
while(a >= b)
{
long long c = b;
for(int i = 0;c <= a ;i++)
{
a -= c;
result += 1<<i;
c = c<< 1;
}
}
if((dividend < 0)^(divisor < 0))
result = -result;
return (int)result;
}
};