Divide Two Integers
Master this topic with zero to advance depth.
Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Examples
10/3 = 3.33333... which is truncated to 3.
7/-3 = -2.33333... which is truncated to -2.
Level I: Brute Force (Linear Subtraction)
Intuition
Keep subtracting the divisor from the dividend until the dividend becomes smaller than the divisor. The number of times we subtract is the quotient.
Thought Process
- Handle edge cases (overflow for
INT_MIN). - Determine sign of result.
- Take absolute values of
dividendanddivisor. - Loop while
dividend >= divisor:dividend -= divisor.count++.
- Apply sign and return.
Pattern: Simulation
Level II: Recursive Long Division
Intuition
The exponential subtraction can be performed recursively. In each call, we find the largest multiple of the divisor that can be subtracted and then recurse on the remainder.
Level III: Optimal (Exponential Subtraction / Shifts)
Intuition
Instead of subtracting exactly one divisor at a time, we subtract the largest possible multiple of the divisor using bit shifts (divisor << k). This is equivalent to long division in binary.
Thought Process
- While
dividend >= divisor:- Find the largest such that
divisor << k <= dividend. dividend -= (divisor << k).quotient += (1 << k).
- Find the largest such that
- This uses the property that is a fast way to find large chunks to subtract.
Pattern: Exponential Backoff / Long Division
Detailed Dry Run
15 / 3
- Largest shift: 3 << 2 = 12. 15 - 12 = 3. Quotient = 4 (2^2).
- Largest shift: 3 << 0 = 3. 3 - 3 = 0. Quotient = 4 + 1 = 5. Result: 5
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.