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
- Subtracting the divisor one copy at a time is O(dividend), far too slow for 2³¹.
- Subtract the largest
divisor · 2^kthat fits, and add2^kto the quotient. That's long division in base 2.
Approach
- Handle overflow:
(-2³¹) / (-1)→ return2³¹ − 1. - Work with absolute values, and remember the sign (negative iff exactly one operand is negative).
- For k from 31 down to 0: if
(a >> k) ≥ b, i.e.b << k ≤ awithout overflowing, thena −= b << kandq += 1 << k. - 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 qJavaScript 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;
}