Saturday, March 2, 2013

[LeetCode] Divide Two Integers

Thought:
Bit manipulation. Take care of the Integer.MAX_VALUE and Integer.MIN_VALUE

Code:
public class Solution {
    public int divide(int dividend, int divisor) {
        int a = Math.abs(dividend);
        int b = Math.abs(divisor);
        boolean neg = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);  
        if (divisor == 0) return Integer.MAX_VALUE;
        if (divisor == Integer.MIN_VALUE) {
            return dividend == divisor? 1: 0;
        }
        if (dividend == Integer.MIN_VALUE) {
            return neg? divide(dividend + b, b) - 1: 1 - divide(dividend + b, b);
        }        
        int product = b, result = 0;
        while (a >= b) {
            int q = 1;
            while (a - product >= product) {
                q = q << 1;
                product = product << 1;
            }
            a -= product;
            product = b;
            result += q;
        }
        return neg? -result: result;
    }
}

No comments:

Post a Comment