原题链接
开始直接累加,超出时间限制,看了别人的题解改用二分法
class Solution {
public:
int divide(int dividend, int divisor) {
//排除一些特殊情况
if(divisor==0)
return 0;
if(divisor==1)
return dividend;
if(divisor==-1)
if(dividend>INT_MIN)
return -dividend;
else
return INT_MAX;
//判断结果符号
int sign;
if((dividend>0&&divisor>0)||(dividend<0&&divisor<0))
sign=1;
else
sign=-1;
long a=dividend;
long b=divisor;
int result=0;
//全部取正
if(a<0)
a=-a;
if(b<0)
b=-b;
result=div(a,b);
return sign*result;
}
//二分法
int div(long a,long b)
{
if(a<b)
return 0;
long tb=b;
int count=1;
while(tb+tb<a)
{
count=count*2;
tb=tb*2;
}
return count+div(a-tb,b);
}
};
非递归写法:
class Solution {
public:
int find2(long dividend,long divisor)
{
int b=divisor;
int ans=0;
while(dividend>=divisor)
{
int res=1;
while(divisor+divisor<dividend)
{
res=res*2;
divisor=divisor*2;
}
dividend=dividend-divisor;
divisor=b;
ans=ans+res;
}
return ans;
}
int divide(int dividend, int divisor) {
if(dividend==divisor)
return 1;
if(divisor==1)
return dividend;
if(divisor==-1)
return dividend==INT_MIN?INT_MAX:-dividend;
int sign;
if((dividend<0&&divisor<0)||(dividend>0&&divisor>0))
sign=1;
else
sign=-1;
long a=dividend;
long b=divisor;
if(a<0)
a=-a;
if(b<0)
b=-b;
int result=find2(a,b);
return result*sign;
}
};