Tuesday, April 28, 2015

[LeetCode] Divide Two Integers

Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
For the function int divide(int dividend, int divisor), overflow will have happen when
1) divisor is 0
2) dividend is -INT_MAX -1 and divisor is -1. for the range of 32 bit integer is from −(231) to 231 − 1
class Solution {
public:
    int divide(int dividend, int divisor) 
    {      
        if(0 == divisor) return INT_MAX;
        if(-1 == divisor && dividend == -INT_MAX - 1) return INT_MAX;
        long longDividend = abs((long)dividend);   
        long longDivisor = abs((long)divisor);   

        long div = longDividend;
        long res = 0;
        while(div >= longDivisor )
        {
            int i =0;
            while(div >= longDivisor)
            {
                i++;
                div >>= 1;
            }
            if(i == 0) i = 1;
            res += (1 << (i-1));
            div = longDividend - (longDivisor << (i-1));
            longDividend = div;
        }
        return ((dividend<0)^(divisor<0)?-1:1)* res;
    }
};