首页 > 代码库 > [leetcode] 29 Divide Two Integers

[leetcode] 29 Divide Two Integers

问题描述:

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

基本的用减法操作可以实现除法,但是速度较慢。为了加快速度,每次将除数和结果加倍。

代码:

    int divide(int dividend, int divisor) {  //C++
        if(dividend == 0)
            return 0;
        if(divisor ==0 || dividend == -2147483648&&divisor ==-1)
            return 2147483647;
        
        bool sameFlag = true;
        if((dividend >0 && divisor <0 )||(dividend <0 && divisor >0))
            sameFlag = false;
        
        long tmpdividend = (dividend >0)? dividend : -(long)(dividend);
        long tmpdivisor  = (divisor >0) ? divisor  : -(long)(divisor);
        int result = 0;
        
        while(tmpdividend >=tmpdivisor){
            int size = 1;
            long t = tmpdivisor;    
            while(tmpdividend >= t)
            {
                result +=size;
                tmpdividend -= t;
                t = t+t;
                size = size+size;
            }
        }
        
        if(!sameFlag)
            result = -result;
        return result;
    }


[leetcode] 29 Divide Two Integers