[leetcode]29. Divide Two Integers

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

If it's overflow, return INT_MAX.

代码转载

class Solution {
public:
    int divide(int dividend, int divisor)
    {
        long long int ret = divideLong(dividend, divisor);
        if(ret > INT_MAX || ret < INT_MIN)
            return INT_MAX;
        return ret;
    }

    long long int divideLong(long long dividend, long long divisor) {
        // extreme cases
        if(divisor == 0)
            return INT_MAX;
        if(dividend == 0)
            return 0;    
            
        int sign = 1;
        if((dividend < 0) ^ (divisor < 0))        
            sign = -1;

        dividend = abs(dividend);
        divisor = abs(divisor);
        long long ret = 0;
        while(dividend > divisor)
        {
            int shift = 0;
            long long part = 1;
            while(dividend > (divisor << shift))
            {
                part <<= 1;
                shift ++;
            }
            if(dividend == (divisor << shift))
            {
                ret += part;
                break;
            }
            else
            {// dividend < (divisor << shift)
                part >>= 1;
                shift --;
            }
            ret += part;
            dividend -= (divisor << shift);
        }
        if(dividend == divisor)
            ret ++;
            
        return sign * ret;
    }
};


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页