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 - Optimal Solution INPUT 10 / 3 dividend divisor Visual: 10 units +1 left Groups of 3: 3 complete Remainder: 1 (ignored) Constraints: -2^31 <= dividend, divisor <= 2^31-1 No *, /, % operators allowed ALGORITHM STEPS 1 Handle Sign XOR signs: positive result sign = (10>0) == (3>0) = + 2 Use Absolute Values Work with |10| and |3| 3 Bit Shifting Loop Subtract largest 2^n * divisor 3<<1 = 6 (6 <= 10) OK 6<<1 = 12 (12 > 10) STOP quotient += 2, remain = 10-6 = 4 3 <= 4: quotient += 1, remain = 1 3 > 1: DONE 4 Apply Sign + Clamp Result: +3 (within range) Time: O(log n) Space: O(1) n = dividend value FINAL RESULT Integer Division Result 3 Calculation: 10 / 3 = 3.333... truncate --> 3 remainder = 1 (ignored) Output 3 OK - Within 32-bit range -2147483648 <= 3 <= 2147483647 Key Insight: Use bit manipulation (left shift) to find the largest multiple of divisor that fits in the dividend. This simulates division using only subtraction and bit shifts. Each shift doubles the divisor, achieving O(log n) time complexity instead of O(n) from simple subtraction. TutorialsPoint - Divide Two Integers | Optimal Bit Shifting Approach
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