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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code