https://leetcode-cn.com/problems/divide-two-integers/
思路:很无聊的题目……商肯定可以用二进制表示,那么我们就可以模拟这个过程来求。
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend==INT_MIN&&divisor==-1)
return INT_MAX;
if(dividend==divisor)
return 1;
int f=1;
if((dividend>0&&divisor<0)||(dividend<0&&divisor>0))
f=-1;
unsigned int uDividend=abs(dividend);
unsigned int uDividendTmp=uDividend;
unsigned int uDivisor=abs(divisor);
unsigned int tmp=uDivisor;
int times=0;
while(tmp<=uDividendTmp)
{
uDividendTmp-=tmp;
tmp<<=1;
++times;
}
unsigned int ans=0;
while(times>0||tmp>=uDivisor)
{
if(uDividend>=tmp)
{
ans=ans<<1|1;
uDividend-=tmp;
}
else
ans<<=1;
tmp>>=1;
--times;
}
return ans*f;
}
};