Divide Two Integers

    题意是计算a/b,其中a、b均为int,结果也要int。但是计算不允许使用乘法、除法、取模运算。

class Solution 
{
public:
    // Divide two unsigned int once, using binary divide method.
    unsigned int unsigned_divide_once(unsigned int &dividend, unsigned int divisor)
    {
        if (dividend < divisor)
        {
            dividend = 0; // Update dividend.
            return 0;
        }
 
        unsigned int result = 1;
 
        while (divisor < dividend)
        {
            divisor <<= 1;
            result <<= 1;
        }
 
        if (divisor != dividend)
        {
            divisor >>= 1;
            result >>= 1;
        }
 
        dividend -= divisor;
 
        return result;
    }
 
    int divide(int dividend, int divisor) 
    {
        if (divisor == 0) throw 1;
 
        bool negative = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
        unsigned int udividend = dividend < 0 ? -dividend : dividend;
        unsigned int udivisor = divisor < 0 ? -divisor : divisor;
        unsigned int uresult = 0;
 
        while (udividend != 0)
        {
            uresult += unsigned_divide_once(udividend, udivisor);
        }
 
        return negative ? -(int)uresult : (int)uresult;
    }
};
posted @ 2012-09-08 16:20  紫红的泪  阅读(1908)  评论(0编辑  收藏  举报