LeetCode——Divide Two Integers

链接:http://leetcode.com/onlinejudge#question_29

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

思路:把除数向左移位,然后去减被除数;只要小心INT_MIN就可以了,因为abs(INT_MIN)如果不转为long long的话,

返回的仍然是INT_MIN,这个是二补码的特点;也有可能异常,我没有试过。


代码:

class Solution {
public:
    int divide(int dividend, int divisor) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (dividend == 0)
            return 0;
        
        long long sign = -1;
        if ((dividend>0 && divisor>0) || (dividend<0 && divisor<0))
            sign = 1;
            
        long long lDividend = abs((long long)dividend);
        long long lDivisor = abs((long long)divisor);
        vector<long long> lDivisors;
        while (lDivisor <= lDividend) {
            lDivisors.push_back(lDivisor);
            lDivisor <<= 1;
        }
        
        long long result = 0;
        for (int i=lDivisors.size()-1; i>=0; i--) {
            long long count = 0;
            while (lDividend >= lDivisors[i]) {
                lDividend -= lDivisors[i];
                count++;
            }
            result += (count << i);
        }
        
        return (int)(result * sign);
    }
};


你可能感兴趣的:(LeetCode)