Divide Two Integers
Divide Two Integers is LeetCode 29 (Medium). Given two integers dividend and divisor, return dividend / divisor without using multiplication, division or the mod operator.
- Drop the fractional part, so the result is rounded toward zero. A negative result therefore rounds up, not down.
- Assume only 32-bit signed integers can be stored. If the true quotient is larger than 2³¹ − 1, return 2³¹ − 1.
Both inputs can be as large as 2³¹ in size, so the quotient can be about two billion.
- -2³¹ <= dividend, divisor <= 2³¹ - 1
- divisor != 0
Intuition
Every quotient is a sum of powers of two, so the divisor can be removed in doubled chunks, not one copy at a time.
- Doubling is free:
b << 1equalsb × 2without a multiply: the chunksb,2b,4b, … cost one shift each. - Take the biggest chunk that fits: in each round, double
b × 2ᵏuntil the next doubling would be too big, subtract it, and add2ᵏto the quotient. - Why the rounds shrink: after taking
b × 2ᵏ, less thanb × 2ᵏis left (or the next doubling would have fitted). So every round uses a smaller power of two than the last, and there are at most about 31 rounds.
To work around a banned operator, rebuild it from shifts and addition: doubling with << finds the largest power-of-two multiple quickly, and the answer is assembled bit by bit. Pow(x, n) uses the same binary breakdown, and so does multiplying with only addition.
Approach
Before reading on, divide 100 by 7 using only adding, subtracting and doubling. How few subtractions can you get away with, and how do the chunks you used relate to 14 written in binary?
Return early for −2³¹ ÷ −1
If dividend == -2³¹ and divisor == -1, return 2³¹ − 1. The true answer is 2³¹, one more than a 32-bit integer can hold, and it is the only pair of inputs whose quotient does not fit.
Fix the sign, then work with sizes
Set negative to true when exactly one input is below zero. Then let a = |dividend| and b = |divisor|. Working with two non-negative numbers keeps the loop simple. C++ and Java store them as 64-bit long long and long.
Double the chunk while it still fits
Start a round with chunk = b and count = 1. While a >= chunk << 1, shift both left by one. When the loop stops, chunk is the largest b × 2ᵏ that fits into a, and count is that 2ᵏ.
Take the chunk and start again
Subtract chunk from a and add count to the quotient. Repeat rounds while a >= b. Each round removes the largest piece it can, so what is left keeps shrinking until no copy of b fits.
Why the quotient is exact
The counts add up to the number of copies of b that were removed, and the loop stops only when less than one copy is left. So the sum is a ÷ b with the remainder dropped. Putting the sign back gives the answer rounded toward zero.
Code in Python, C++ and Java
Common pitfalls
Taking the absolute value inside an int
int a = Math.abs(dividend); int b = Math.abs(divisor);
long a = Math.abs((long) dividend); long b = Math.abs((long) divisor);
Math.abs(-2147483648) is still -2147483648 in Java, because +2³¹ does not fit in an int (in C++ it is undefined behaviour). For dividend = -2147483648, divisor = 2 the loop condition a >= b is false at once and the code returns 0 instead of −1073741824.
Doubling past the int range
int chunk = b; while (a >= (chunk << 1)) chunk <<= 1;
long chunk = b; while (a >= (chunk << 1)) chunk <<= 1;
For dividend = 2147483647, divisor = 1073741824, chunk << 1 in an int wraps to −2147483648, which is less than a, so the loop keeps doubling into 0 and never stops. A 64-bit chunk has room for the extra bit.
Subtracting one divisor at a time
while a >= b:
a -= b
quotient += 1while a >= b:
chunk, count = b, 1
while a >= chunk << 1:
chunk <<= 1
count <<= 1
a -= chunk
quotient += countIt gives the right answer, but dividend = 2147483647, divisor = 1 takes over two billion loop turns and exceeds the time limit. Doubled chunks finish in at most about 31 rounds.
Edge cases
|dividend| < |divisor|, for example dividend = 3, divisor = 5a >= b is false from the start, so no round runs and the answer is 0.
dividend = -2147483648, divisor = 1Not the overflow pair: the answer −2147483648 fits. With 64-bit a and b the loop handles it like any other input.
Complexity
Divide Two Integers FAQ
Can it be solved without 64-bit integers?
Yes. Turn both inputs negative instead of positive, because −2³¹ fits in an int while +2³¹ does not. Every comparison flips (a <= chunk instead of a >= chunk), and before doubling check chunk >= -2³⁰ so that chunk + chunk cannot wrap. This is the version to give when an interviewer insists on the 32-bit rule.
Is there a faster O(log n) version?
Try each bit from 31 down to 0: if (a >> i) >= b, subtract b << i from a and add 1 << i to the quotient. Comparing a >> i with b avoids shifting b out of range. That is one pass of 32 checks, against up to a few hundred for the doubling rounds. Both are fast enough here.
Why is -7 divided by 2 equal to -3 and not -4?
The exact value is −3.5, and the problem rounds toward zero, which gives −3. Rounding down would give −4. Python's // rounds down (-7 // 2 == -4), which is why the code divides the two sizes, which are both non-negative, and only then puts the minus sign back.