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
assert Solution().divide(10, 3) == 3
assert Solution().divide(7, -3) == -2
assert Solution().divide(-2147483648, -1) == 2147483647
assert Solution().divide(-2147483648, 2) == -1073741824
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
boolean neg = (dividend < 0) != (divisor < 0);
long a = Math.abs((long) dividend), b = Math.abs((long) divisor), q = 0;
while (a >= b) {
int k = 0;
while (a >= (b << (k + 1))) k++;
a -= b << k;
q += 1L << k;
}
return (int) (neg ? -q : q);
}
}
func divide(dividend int, divisor int) int {
if dividend == math.MinInt32 && divisor == -1 {
return math.MaxInt32 // the only overflowing case
}
neg := (dividend < 0) != (divisor < 0)
a, b, q := dividend, divisor, 0
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
for a >= b { // subtract the largest b * 2^k that fits
k := 0
for a >= b<<(k+1) {
k++
}
a -= b << k
q += 1 << k
}
if neg {
return -q
}
return q
}