Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Difficulty:Medium
要解决的问题有两个:
1.溢出的情况是在-2147483648却绝对值的时候,用long long就好
2.一个个减会超时。利用位移,每次减的都是上次的两倍,大大缩短时间,利用循环解决。
int divide(int dividend, int divisor) {
if(dividend ==-2147483648 &&divisor ==-1)
return 2147483647;
if(dividend==0||divisor==0)
return 0;
if(divisor==1)
return dividend;
else if(divisor == -1)
return -dividend;
int cou = 0, flag1 = 0,flag2 = 0;
long long a = dividend;
long long b = divisor;
if(a<0)
{
a = 0-a;
flag1 = 1;
}
if(b<0)
{
b = 0 - b;
flag2 = 1;
}
while(a>=b)
{
long long c = b;
for(int i = 0; a>=c; i++,c<<=1)
{
a = a-c;
cou = cou + (1<<i);
}
}
if(flag1==flag2)
;
else
cou = -cou;
return cou;
}