# [leetcode]29. Divide Two Integers

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

If it's overflow, return INT_MAX.

class Solution {
public:
int divide(int dividend, int divisor)
{
long long int ret = divideLong(dividend, divisor);
if(ret > INT_MAX || ret < INT_MIN)
return INT_MAX;
return ret;
}

long long int divideLong(long long dividend, long long divisor) {
// extreme cases
if(divisor == 0)
return INT_MAX;
if(dividend == 0)
return 0;

int sign = 1;
if((dividend < 0) ^ (divisor < 0))
sign = -1;

dividend = abs(dividend);
divisor = abs(divisor);
long long ret = 0;
while(dividend > divisor)
{
int shift = 0;
long long part = 1;
while(dividend > (divisor << shift))
{
part <<= 1;
shift ++;
}
if(dividend == (divisor << shift))
{
ret += part;
break;
}
else
{// dividend < (divisor << shift)
part >>= 1;
shift --;
}
ret += part;
dividend -= (divisor << shift);
}
if(dividend == divisor)
ret ++;

return sign * ret;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120