Divide Two Integers - Problem

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.

Return the quotient after dividing dividend by divisor.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³¹, 2³¹ − 1]. For this problem, if the quotient is strictly greater than 2³¹ - 1, then return 2³¹ - 1, and if the quotient is strictly less than -2³¹, then return -2³¹.

Input & Output

Example 1 — Basic Division
$ Input: dividend = 10, divisor = 3
Output: 3
💡 Note: 10 ÷ 3 = 3.33, truncated toward zero gives 3
Example 2 — Exact Division
$ Input: dividend = 7, divisor = -3
Output: -2
💡 Note: 7 ÷ (-3) = -2.33, truncated toward zero gives -2
Example 3 — Overflow Case
$ Input: dividend = -2147483648, divisor = -1
Output: 2147483647
💡 Note: Result would be 2147483648, but we cap at 2³¹-1 = 2147483647

Constraints

  • -2³¹ ≤ dividend, divisor ≤ 2³¹ - 1
  • divisor ≠ 0

Visualization

Tap to expand
Divide Two Integers: 10 ÷ 3 = ?dividend = 10divisor = 3❌ Cannot use: ×, ÷, % operators✅ Can use: +, -, bit shifts (<<, >>)Approach 1: Subtract 3 repeatedly10-3=7, 7-3=4, 4-3=1 (3 times)Approach 2: Use bit shifts3→6 (take 6), remainder 4→3 (take 3)Result: 3
Understanding the Visualization
1
Input
Two integers: dividend and divisor
2
Process
Use bit shifts to find multiples of divisor
3
Output
Quotient truncated toward zero
Key Takeaway
🎯 Key Insight: Use exponential search with bit shifts to find the largest multiple of divisor that fits, avoiding slow repeated subtraction
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
98.0K Views
Medium Frequency
~25 min Avg. Time
4.2K 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