sagelearnai

Divide Two Integers

Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #29

Divide two 32-bit integers without using multiplication, division or the mod operator. Truncate toward zero. If the result overflows the 32-bit signed range, return 2³¹ − 1.

Examples

text
dividend = 10, divisor = 3    →  3
dividend = 7, divisor = -3    →  -2
dividend = -2147483648, divisor = -1  →  2147483647   (overflow clamp)

Hints

  1. Subtracting the divisor one copy at a time is O(dividend), far too slow for 2³¹.
  2. Subtract the largest divisor · 2^k that fits, and add 2^k to the quotient. That's long division in base 2.

Approach

  1. Handle overflow: (-2³¹) / (-1) → return 2³¹ − 1.
  2. Work with absolute values, and remember the sign (negative iff exactly one operand is negative).
  3. For k from 31 down to 0: if (a >> k) ≥ b, i.e. b << k ≤ a without overflowing, then a −= b << k and q += 1 << k.
  4. Apply the sign.

That's O(32) iterations. Checking (a >> k) >= b instead of (b << k) <= a avoids overflowing the shifted divisor. JavaScript's bitwise operators work on 32-bit signed values, so the JS version uses arithmetic doubling on plain numbers instead.

Complexity

Time: O(log² n) for the doubling version, O(32) for the bit loop. Space: O(1).

Python solution
def divide(dividend, divisor):
    INT_MAX, INT_MIN = 2 ** 31 - 1, -2 ** 31
    if dividend == INT_MIN and divisor == -1:
        return INT_MAX
    neg = (dividend < 0) != (divisor < 0)
    a, b = abs(dividend), abs(divisor)
    q = 0
    for k in range(31, -1, -1):
        if (a >> k) >= b:
            a -= b << k
            q += 1 << k
    return -q if neg else q
JavaScript solution
function divide(dividend, divisor) {
  const INT_MAX = 2 ** 31 - 1;
  if (dividend === -(2 ** 31) && divisor === -1) return INT_MAX;
  const neg = (dividend < 0) !== (divisor < 0);
  let a = Math.abs(dividend), q = 0;
  const b = Math.abs(divisor);
  while (a >= b) {
    let chunk = b, mult = 1;
    while (chunk + chunk <= a) { chunk += chunk; mult += mult; }
    a -= chunk; q += mult;
  }
  return neg ? -q : q;
}