Monday, April 24, 2017

29. Divide Two Integers


e.g.
20 / 4
-> 20 = 4 * 5  -> result  =  5 = (101) = 1 * 2^2 + 0 * 2^1 + 1 * 2^0
-> 20 = 4 * (1 * 2^2 + 0 * 2^1 + 1 * 2^0)
-> 20 = (1 * 4 << 2) + (0 * 4<<1) + (1 * 4 << 0)
-> (20 >= (4 << 2)) then bit = 1 -> 20 - (4 << 2)) = 4
-> (4 < (0 * 4<<1)) then bit = 0 -> 4 - 0 = 4
->  (4 >=  (4 << 0)) then bit = 1 -> 4 - 4 = 0


beats 31.79 %

class Solution {
    public int divide(int dividend, int divisor) {
        int result = 0;
        if (divisor == Integer.MIN_VALUE) {
            result = dividend == divisor ? 1 : 0;
        } else if (dividend == Integer.MIN_VALUE && divisor == -1) {
            result = Integer.MAX_VALUE;
        } else if (dividend == Integer.MIN_VALUE && divisor == 1) {
            result = dividend;
        } else {
            boolean isNegative = ((dividend >>> 31) ^ (divisor >>> 31)) == 1;
            // System.out.println(isNegative);
            dividend = Math.abs(dividend);
            divisor = Math.abs(divisor);
            int bit = 0;
            while ((dividend >>> bit) - divisor > 0) {
                bit++;
            }
            // System.out.println("->" + bit);
            while (bit >= 0) {
                if ((dividend >>> bit) - divisor >= 0) {
                    dividend -= divisor << bit;
                    result += 1 << bit;
                }
                bit--;
            }
            if (isNegative) {
                result = -result;
            }
        }
        return result;
     
    }
}


No comments:

Post a Comment