问题描述:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
分析:这道题不允许用*/和%运算,因此只能模拟计算机对乘除法的做法来进行。请参考另外一篇博客:这里写链接内容另外,这道题最恶心的是一些边界值。如被除数为-2147483648;除数为:-2147483648;或者为+1,-1等等情况。
代码如下:4ms
int getBits(int num){
int numLen = 0;
while(num){
numLen++;
num = num>>1;
}
return numLen;
}
int getBit(int num,int pos){//获取从右到左的第pos位置的值1/0
pos = pos-1;
int index = 1<<pos;
if((num&index)>>pos)
return 1;
else
return 0;
}
int divide(int dividend, int divisor) {
int divide = 0;
int res = 0;
bool minus = false;
bool minValue = false;
if(dividend<0||divisor<0){
if(dividend<0&&divisor<0)
{
dividend = -dividend;
divisor = -divisor;
}else{
dividend = dividend<0?-dividend:dividend;
divisor = divisor<0?-divisor:divisor;
minus = true;
}
if(dividend==-2147483648){
minValue = true;
dividend = dividend-1;
}
if(divisor==-2147483648){
if(minValue)//被除数与除数相同
return 1;
return 0;
}
}
if(dividend<divisor)
return 0;
if(divisor==1){
if(minus){
if(minValue)//被除数为最大值
return -dividend-1;
else
return -dividend;
}
else
return dividend;
}
int index = getBits(dividend);
while(index>0){
int val = getBit(dividend,index--);
divide = (divide<<1)+val;
if(divide<divisor)
res = res<<1;
else{
res = (res<<1)+1;
divide = divide-divisor;
}
}
if(minValue&&(divide+1)>=divisor){
res++;
divide = divide+1-divisor;
}
if(minus){
return -res;
}
return res;
}