Wednesday, January 7, 2015

LeetCode 29: Divide Two Integers

Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
public class Solution {
    public int divide(int dividend, int divisor) {
        // Aodpt shift operation simulate divide simulation.
        // Left shift 1 means multiplying 2;
        // Right shift 1 means dividing 2.
        // 1. We shift the divisor 'q' left until it is just larger than dividend 'p'.
        // 2. Then we can add the shifted value to the result and subtract the shifted value from dividend.
        // 3. Keep doing this until dividend 'p' is smaller than divisor 'q'.
        // In fact, every integer can be represented by a set of base 2 so that shifting can be used.
        long result = 0;
        long p = Math.abs((long)dividend);
        long q = Math.abs((long)divisor);
        long base = 1; // Note: If 'base' is 'int' type, the number may overflow.

        while (p >= q)
        {
            int counter = 0;
            
            while (p >= (q << counter))
                counter++;
            
            result += base << (counter - 1);
            p -= q << (counter - 1);
        }
        
        if (dividend>0 ^ divisor>0)
        {
            result = -result;
            
            if (result < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
            else
                return (int)result;            
        }
        else
        {
            if (result > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            else
                return (int)result;
        }
    }
}

No comments:

Post a Comment