[LeetCode] Divide Two Integers

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

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(divisor == 0)    exit(1);
        long long a = abs((long long)dividend);
        long long b = abs((long long)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;
            }
        }
        return ((dividend ^ divisor) >> 31) ? -res : res;
    }
};
参考:http://blog.csdn.net/doc_sgl/article/details/12841741

你可能感兴趣的:([LeetCode] Divide Two Integers)