首页 > 代码库 > leet code -- Divide Two Integers

leet code -- Divide Two Integers

Q: Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT.

分析:设被除数为p,除数为q.则有:
p = q * (1+2+4+...+ 2^(exp2-1)) + new_p
每一轮循环除数翻倍增加:q=q+q,p=p-q直到最后的p小于除数q,此时被除数还剩new_p.
将(new_p,q)进行递归操作.
递归的出口是:p=0.
注意:需要注意的是,int类型范围是[-2^31, 2^31-1],最高位为补码形式符号位!
当被除数p=-2^(31)=0x1<<31时,divide(-2^31, -1) = 2^31 - 1!! 0x1<<31默认int类型,值为-2^31.

class Solution {
public:
    int divide(long long dividend, long long divisor) {                                                                               
        int exp2 = 0;
        long long ret;
        long long p = abs(dividend), q = abs(divisor);
        if(p < q)     //递归出口
            return 0;

        while(p - q >= 0){
            p -=  q;
            q = q + q;
            exp2++;
        }
        ret = divide(p, abs(divisor));    //figure out new_p
        ret += (0x1 << exp2) - 1;
        if(dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0)
            ret = -ret;
        if(ret >= (unsigned int)(0x1<<31)) --ret;
        return ret;
    }
};




leet code -- Divide Two Integers