Given two integers, dividend and divisor, return dividend divided by divisor, without using the multiply, divide or remainder operators.
Drop any fractional part: the quotient is cut toward zero, so 9 ÷ 4 gives 2 and −9 ÷ 4 gives −2. Answers must fit a signed 32-bit integer; if the true quotient is above 2^31 − 1, return 2^31 − 1 instead.
Example 1
Input: dividend = 20, divisor = 3 Output: 6 Why: 20 ÷ 3 is 6.67, and the fraction is dropped
2 more examples and the constraints
Example 2
Input: dividend = 17, divisor = -5 Output: -3 Why: 17 ÷ −5 is −3.4, cut toward zero to −3
Example 3
Input: dividend = -2147483648, divisor = -1 Output: 2147483647 Why: 2^31 does not fit in 32 bits, so the answer is capped
Constraints
- −2,147,483,648 ≤ dividend, divisor ≤ 2,147,483,647 (the 32-bit range)
- divisor ≠ 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Subtract doubled chunksO(log² n)
- Build the doubling table onceO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,147,483,647 ÷ 1 | Verdict |
|---|---|---|---|
| Subtract doubled chunks | O(log² n) | Passes; about 500 doublings | |
| Build the doubling table once | O(log n) | Best; about 31 doublings |
n = |dividend|. Plain repeated subtraction would be O(n): two billion steps.
Edge cases to test
- The one overflow. −2,147,483,648 ÷ −1 would be 2^31, so return 2,147,483,647.
- The smallest dividend. −2,147,483,648 has no positive 32-bit twin, so take its size in 64 bits (Python ints never overflow).
- Divisor bigger than dividend. 1 ÷ 2 and 7 ÷ −2,147,483,648 both give 0.
- Mixed signs. −7 ÷ 2 is −3, not −4: the result is cut toward zero.
- Dividend 0. The answer is 0 for any divisor.
Common mistakes
- Subtracting the divisor one at a time, which takes billions of steps for ÷ 1.
- Taking abs of −2^31 in a 32-bit int, which overflows and stays negative.
- Rounding down instead of toward zero for negative results, so −7 ÷ 2 gives −4.
How to talk through it
- 1Clarify. Truncate toward zero? What should happen when the quotient does not fit in 32 bits?
- 2Start simple. Repeated subtraction is correct but takes up to two billion steps.
- 3Double the step. Add the divisor to itself to get chunks 1, 2, 4, ... times as big, and take the biggest that fits.
- 4Handle signs once. Work with sizes, special-case −2^31 ÷ −1, and negate at the end if the signs differ.
- 5Test out loud. Run 20 ÷ 3, 17 ÷ −5, −2^31 ÷ −1, −2^31 ÷ 1 and 1 ÷ 2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?