Divide Two Integers
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Divide Two Integers
Given two integers
dividend and divisor, divide two integers without using multiplication, division, and mod operator.Examples
Input: dividend = 10, divisor = 3
Output: 3
10/3 = 3.33333... which is truncated to 3.
Input: dividend = 7, divisor = -3
Output: -2
7/-3 = -2.33333... which is truncated to -2.
Approach 1
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
⏱ O(N) - Where $N$ is the quotient. Extremely slow for large dividends.💾 O(1) - Constant space.
Approach 2
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.
⏱ $O(\log^2 N)$💾 $O(\log N)$ (Recursion stack)
Approach 3
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
⏱ O(log^2 N) - Outer loop reduces dividend, inner loop finds shift.💾 O(1) - Constant space.
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
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.