题目:
Divide two integers without using multiplication, division and mod operator.
思路:
1)考虑边界问题。
2)考虑INT_MIN与INT_MAX绝对值之间差1。
3)考虑符号。 类似
http://blog.csdn.net/lanxu_yy/article/details/11686447,将被除数以除数的1次方,2次方,2的2次方…2的n次方来分解。
代码:
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend==0||divisor==0)
{
return 0;
}
bool positive=true;
if(dividend>0&&divisor<0)
{
positive = false;
}
if(dividend<0&&divisor>0)
{
positive = false;
}
int x=dividend;
int y=divisor;
int result = 0;
if(divisor==INT_MIN)
{
return dividend==INT_MIN?1:0;
}else if(divisor<0)
{
y=-divisor;
}
if(dividend==INT_MIN)
{
x=INT_MAX-y+1;
result+=1;
}else if(dividend<0)
{
x=-dividend;
}
while(x>=y)
{
int sum = y;
int count=1;
while(sum <= x - sum)
{
count += count;
sum += sum;
};
x -= sum;
result+=count;
};
return (positive?1:-1)*result;
}
};