Divide Two Integers - Problem
Divide Two Integers

Welcome to a fascinating mathematical puzzle! Your mission is to implement division without using division.

Given two integers dividend and divisor, you need to divide them without using multiplication (*), division (/), or modulo (%) operators.

Key Requirements:
• The result should truncate toward zero (remove fractional part)
• Handle 32-bit integer overflow by clamping to [-2³¹, 2³¹ - 1]
• Examples: 8.345 → 8, -2.7335 → -2

This problem tests your understanding of bit manipulation and creative mathematical thinking!

Input & Output

example_1.py — Basic Division
$ Input: dividend = 10, divisor = 3
Output: 3
💡 Note: 10/3 = 3.333... which truncates to 3
example_2.py — Negative Result
$ Input: dividend = 7, divisor = -3
Output: -2
💡 Note: 7/(-3) = -2.333... which truncates toward zero to -2
example_3.py — Overflow Case
$ Input: dividend = -2147483648, divisor = -1
Output: 2147483647
💡 Note: This would result in 2147483648, but we clamp to 2^31-1 = 2147483647

Visualization

Tap to expand
Efficient Division: 100 ÷ 7 = 14Step 1: Double until we exceed dividend7×1=77×2=147×4=287×8=567×16=112❌Step 2: Largest fit is 7×8=56100 - 56 = 44, quotient = 8Step 3: Repeat with remainder 447×1=77×2=147×4=287×8=56❌Step 4: Largest fit is 7×4=2844 - 28 = 16, quotient = 8 + 4 = 12Step 5: Continue...16 - 14 = 2, quotient = 12 + 2 = 14Final Answer: 100 ÷ 7 = 14 (remainder 2)
Understanding the Visualization
1
Start Small
Begin with divisor×1, then double repeatedly
2
Find Maximum
Stop doubling when next value exceeds dividend
3
Subtract & Repeat
Subtract largest multiple and repeat with remainder
4
Build Result
Sum all multipliers to get final quotient
Key Takeaway
🎯 Key Insight: By doubling multiples using bit shifts, we reduce O(n) subtraction to O(log²n) by finding large chunks efficiently!

Time & Space Complexity

Time Complexity
⏱️
O((log dividend)²)

For each bit position, we do logarithmic work to find the largest multiple

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • -231 ≤ dividend, divisor ≤ 231 - 1
  • divisor ≠ 0
  • Cannot use multiplication, division, or mod operators
  • Result must be clamped to 32-bit signed integer range
Asked in
Facebook 45 Google 38 Microsoft 32 Amazon 28
89.4K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen