您的位置:首页 > 其它

[leetcode Q29] Divide Two Integers

2016-02-29 13:08 176 查看

1. 题目

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


If it is overflow, return MAX_INT.

要求不使用乘除法实现两个整数相除运算。

2. 思路

不使用乘法除法,要想快数得到结果就只能考虑位运算。本题主要考察位运算。

被除数减去一次除数,结果 + 1

被除数减去
2 x 除数
,结果 + 2

被除数减去
4 x 除数
,结果 + 4

……

需要注意整数溢出

如输入:

[code]-2147483648
1
-2147483648
-1


3. 实现

[code]class Solution {
public:
    int divide(int dividend, int divisor) {
           // Note: The Solution object is instantiated only once.  
            if (divisor == 1)
                return dividend;
            long long a = abs((double)dividend);  
            long long b = abs((double)divisor);  
            long long res = 0;  
            while(a >= b)  
            {  
                long long c = b;  
                for(int i = 0; a >= c; i++, c <<=1)  
                {  
                    a -= c;  
                    res += 1<<i;  
                }  
            }

            if (res == 0x80000000)
                return 2147483647;
            else
                return ((dividend ^ divisor) >> 31) ? (-res) : (res);  
        }  
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: