29 Divide Two Integers

1. Question

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

If it is overflow, return MAX_INT.

2. Implementation

(1) 倍增法

class Solution {
    public int divide(int dividend, int divisor) {
        long a = Math.abs((long)dividend);
        long b = Math.abs((long)divisor);
        long res = 0;

        while (a >= b) {
            long temp = b;
            int i = 0;

            while (a >= temp) {
                a -= temp;
                temp <<= 1;
                res += 1 << i;
                ++i;
            }
        }

        if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0) {
            res = -res;
        }
        return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)res;
    }
}

3. Time & Space Complexity

倍增法:时间复杂度O(log(divisor)), 空间复杂度O(1)

Last updated