LeetCode 29 - Divide Two Integers

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

If it is overflow, return MAX_INT.

 

Solution:

public int divide(int dividend, int divisor) {
    if(divisor == 0 || (dividend==Integer.MIN_VALUE&&divisor==-1)) {
        return Integer.MAX_VALUE;
    }

    long a = dividend;
    long b = divisor;
    a = a > 0 ? a : -a;
    b = b > 0 ? b : -b;

    int result = 0;
    while (a >= b) { // i.e. 5, 2
        // long c = b;
        // for (int i = 0; a >= c; i++, c <<= 1) {
        //     a -= c;
        //     result += 1<<i;
        // }
        for (int i = 0; a >= (b<<i); i++) {
            a -= (b<<i);
            result += 1<<i;
        }
    }
    int signum = (dividend ^ divisor) >>> 31;
    return signum == 1 ? -result : result;
}

 

你可能感兴趣的:(LeetCode)