Wednesday, February 12, 2014

Leetcode: Divide Two Integers

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

Solution:

The result can be seen as $a_n 2^n+ a_{n-1} 2^{n-1}+\dots+a_1 *2 +a_0$, with $a_i \in \{0,1\}$. Our solution calculates first n by obtaining the largest n that $\text{divisor} \cdot 2^n \leq \text{dividend}$. Then we just have to calculate $a_i = \left( \text{dividend} - \sum_{j=i+1}^n a_j \text{divisor} \cdot 2^j\right)>= 2^i$, even the expression is complex the code is much simpler:
We had to change integers into longs to avoid the overflowing problem of -Integer.MIN_VALUE cannot be contained in an int.

public class Solution {
    public int divide(int dividend, int divisor) {
        long dividendL = dividend<0 ?-(long)dividend : (long)dividend;
        long divisorL = divisor<0 ? -(long)divisor : (long)divisor;
        if(dividendL<divisorL) return 0;
        long temp =divisorL;
        long result=0;
        long i=1;

        //We calculate n and 2^n
        while((temp<<1)<=dividendL)
        {
            temp<<=1;
            i<<=1;
        }
        
        //We calculate a_i and acumulate them in result
        while (dividendL>0 && i>0)
        {
            if(temp<=dividendL)
            {
                dividendL-=temp;
                result +=i;
            }
            temp>>=1;
            i>>=1;
        }
        return ((dividend & 0x80000000)^(divisor & 0x80000000)) ==0 ? (int)result : (int)(-result);
    }
}

No comments :

Post a Comment