[LeetCode]Divide Two Integers

Divide Two Integers

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

不用*, /, %来实现除法。

注意:1.正负号;2.INT_min=-2147483648,变为正数越界。

const int INTMIN = -2147483648;

class Solution {
public:

    int divide(int dividend, int divisor) {
        if (divisor == INTMIN) return dividend == INTMIN ? 1 : 0;
        if (divisor < 0) return -divide(dividend, -divisor);
        
        if (dividend == INTMIN) return -1-divide(-divisor-dividend, divisor);
        if (dividend < 0) return -divide(-dividend, divisor);
        if (dividend < divisor) return 0;
        
        int d, s, rd, rs;
        d = rd = divisor;
        s = rs = 1;
        while (d << 1 > 0 && d << 1 < dividend) {
            s <<= 1;
            d <<= 1;
        }
        return s + divide(dividend - d, divisor);
    }
};
 

你可能感兴趣的:(LeetCode)