Wednesday, March 23, 2016

[LeetCode] 29. Divide Two Integers


Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.

INT_MAX AND INT_MIN is not symmetric. Java abs(INT_MIN) returns INT_MIN as well. 1. Use long to solve it.
public class Solution {
    public int divide(int dividend, int divisor) {
        
        // 00100101
        // 00000011

        if (divisor == 0 || dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;

        int res = 0;
        
        boolean sign  = dividend > 0 ^ divisor > 0 ? false : true;
        
        long dividendl = Math.abs((long)dividend), divisorl = Math.abs((long)divisor);
        
        while(dividendl >= divisorl){
            long k = divisorl;
            int q = 1;
            while((k << 1) <= dividendl){
                k <<= 1;
                q <<= 1;
            }
            res += q;
            dividendl -= k;
        }
        
        if(sign)
            return res;
        else
            return (res^-1) + 1;
    }
}

2. Handle the boarder condition, when INT_MIN as dividend: dividend - divisor, ++res will solve the boarder problem.


No comments:

Post a Comment