SDE & MLE Prep

29. Divide Two Integers

Problem

Divide two 32-bit integers without using multiplication, division or the modulo operator, truncating toward zero. If the result is outside [−2³¹, 2³¹ − 1], return the nearest bound.

Example: 10 / 3 → 3; 7 / -3 → -2

Constraints: divisor ≠ 0; assume only 32-bit integers are available.

No *, /, %: subtract the largest doubled divisor (divisor << k) that fits, adding 1 << k to the quotient. Work with negatives (or longs) to dodge the −2³¹ overflow; the only overflow case is −2³¹ / −1.

Complexity: O(log² n) (O(log n) with a precomputed shift list).

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        if dividend == -2 ** 31 and divisor == -1:
            return 2 ** 31 - 1
        neg = (dividend < 0) != (divisor < 0)
        a, b, q = abs(dividend), abs(divisor), 0
        while a >= b:
            k = 0
            while a >= b << (k + 1):
                k += 1
            a -= b << k
            q += 1 << k
        return -q if neg else q