LeetCode #29 Medium

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.

Constraints
  • -2³¹ <= dividend, divisor <= 2³¹ - 1
  • divisor != 0
bit-manipulationmathsbinary-search
Open on LeetCode ↗
02

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 << 1 equals b × 2 without a multiply: the chunks b, 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 add 2ᵏ to the quotient.
  • Why the rounds shrink: after taking b × 2ᵏ, less than b × 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.
How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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ᵏ.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def divide(self, dividend, divisor):
▶3 if dividend == -2**31 and divisor == -1:
▶4 return 2**31 - 1
▶5 negative = (dividend < 0) != (divisor < 0)
▶6 a, b = abs(dividend), abs(divisor)
▶7 quotient = 0
▶8 while a >= b:
▶9 chunk, count = b, 1
▶10 while a >= chunk << 1:
▶11 chunk <<= 1
▶12 count <<= 1
▶13 a -= chunk
▶14 quotient += count
▶15 return -quotient if negative else quotient
22÷3sign+|dividend|22not taken yetleft22chunks this roundnonequotientsame signs → answer is positive
negativeFalse
a22|dividend|
b3|divisor|
The sign is decided first, from the original inputs: the answer is negative exactly when one input is negative and the other is not. After that the work uses only the sizes 22 and 3, so the loop never has to think about signs.
22÷3sign+|dividend|22not taken yetleft22chunks this round3×1quotientleft 22 ≥ 3 → start a round with 3
a22left
chunk3
count1
At least one more copy of 3 fits into what is left (22), so a new round starts. The round begins with one copy, 3 × 1, and tries to grow it by doubling.
22÷3sign+|dividend|22not taken yetleft22chunks this round3×16×2quotient6 ≤ 22 → double to 6 (×2)
chunk6chunk << 1
count2count << 1
Twice the current chunk is 6, which still fits into 22. Shifting left by one doubles a number without multiplying, so the chunk becomes 6 and it stands for 2 copies of 3.
22÷3sign+|dividend|22not taken yetleft22chunks this round3×16×212×4quotient12 ≤ 22 → double to 12 (×4)
chunk12chunk << 1
count4count << 1
Twice the current chunk is 12, which still fits into 22. Shifting left by one doubles a number without multiplying, so the chunk becomes 12 and it stands for 4 copies of 3.
22÷3sign+|dividend|22not taken yetleft22chunks this round3×16×212×424×8quotient24 > 22 → stop at 12 (×4)
chunk << 124too big
chunk12
Doubling again would give 24, more than the 22 that is left. So 12 is the biggest chunk of the form 3 × 2ᵏ that fits, and the round will take it.
22÷3sign+|dividend|2212left 10left10chunks this round3×16×212×4quotient4=4take 12 → left 10, quotient 4
a10left
quotient4
Subtract the chunk: 22 − 12 = 10. The chunk was 4 copies of 3, so 4 is added to the quotient. What is left is now less than this chunk, so any later round uses a smaller one.
22÷3sign+|dividend|2212left 10left10chunks this round3×1quotient4=4left 10 ≥ 3 → start a round with 3
a10left
chunk3
count1
At least one more copy of 3 fits into what is left (10), so a new round starts. The round begins with one copy, 3 × 1, and tries to grow it by doubling.
22÷3sign+|dividend|2212left 10left10chunks this round3×16×2quotient4=46 ≤ 10 → double to 6 (×2)
chunk6chunk << 1
count2count << 1
Twice the current chunk is 6, which still fits into 10. Shifting left by one doubles a number without multiplying, so the chunk becomes 6 and it stands for 2 copies of 3.
22÷3sign+|dividend|2212left 10left10chunks this round3×16×212×4quotient4=412 > 10 → stop at 6 (×2)
chunk << 112too big
chunk6
Doubling again would give 12, more than the 10 that is left. So 6 is the biggest chunk of the form 3 × 2ᵏ that fits, and the round will take it.
22÷3sign+|dividend|22126left 4left4chunks this round3×16×2quotient4+2=6take 6 → left 4, quotient 6
a4left
quotient6
Subtract the chunk: 10 − 6 = 4. The chunk was 2 copies of 3, so 2 is added to the quotient. What is left is now less than this chunk, so any later round uses a smaller one.
22÷3sign+|dividend|22126left 4left4chunks this round3×1quotient4+2=6left 4 ≥ 3 → start a round with 3
a4left
chunk3
count1
At least one more copy of 3 fits into what is left (4), so a new round starts. The round begins with one copy, 3 × 1, and tries to grow it by doubling.
22÷3sign+|dividend|22126left 4left4chunks this round3×16×2quotient4+2=66 > 4 → stop at 3 (×1)
chunk << 16too big
chunk3
Doubling again would give 6, more than the 4 that is left. So 3 is the biggest chunk of the form 3 × 2ᵏ that fits, and the round will take it.
22÷3sign+|dividend|221263left1chunks this round3×1quotient4+2+1=7take 3 → left 1, quotient 7
a1left
quotient7
Subtract the chunk: 4 − 3 = 1. The chunk was one copy of 3, so 1 is added to the quotient. What is left is now less than this chunk, so any later round uses a smaller one.
22÷3sign+|dividend|221263left1chunks this roundnonequotient4+2+1=7left 1 < 3 → no copy fits, stop
a1left over
quotient7
Only 1 is left, which is less than 3. It is the remainder, and it is dropped: the problem wants the quotient rounded toward zero.
22÷3sign+|dividend|221263left1chunks this roundnonequotient4+2+1=7→7return 7
result7
The chunks taken add up to the quotient: 4 + 2 + 1 = 7. Each count is a power of two, so the rounds have written out the binary digits of the answer.
05

Common pitfalls

Taking the absolute value inside an int

✗ Wrong
int a = Math.abs(dividend);
int b = Math.abs(divisor);
✓ Right
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

✗ Wrong
int chunk = b;
while (a >= (chunk << 1)) chunk <<= 1;
✓ Right
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

✗ Wrong
while a >= b:
    a -= b
    quotient += 1
✓ Right
while a >= b:
    chunk, count = b, 1
    while a >= chunk << 1:
        chunk <<= 1
        count <<= 1
    a -= chunk
    quotient += count

It 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.

06

Edge cases

|dividend| < |divisor|, for example dividend = 3, divisor = 5

a >= b is false from the start, so no round runs and the answer is 0.

dividend = -2147483648, divisor = 1

Not the overflow pair: the answer −2147483648 fits. With 64-bit a and b the loop handles it like any other input.

07

Complexity

Time
O(log² n)
Space
O(1)
n is |dividend|. There are at most about 31 rounds, and each round doubles at most about 31 times, so even the worst 32-bit input takes a few hundred steps. Only a handful of variables are stored.
08

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.