Divide Two Integers

Medium

Topics
MathBit Manipulation

Given two integers dividend and divisor, divide them without using multiplication, division, or the modulo operator.

The integer division should truncate toward zero, so 8.345 becomes 8 and -2.7335 becomes -2.

Assume 32-bit signed integers. If the true quotient exceeds the representable range, return 2^31 - 1.

Example 1

76543210dividend000010103«1 = 6000001103«0 = 300000011
Division without /: repeatedly subtract the largest doubling of the divisor that still fits, which is a left shift. Each row is one such doubling, so the quotient is built bit by bit instead of by counting subtractions one at a time. 10 / 3 = 3.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  a = 10, b = 3
Output: 3
Explanation: 10 / 3 = 3.333 truncates to 3.

Example 2

76543210dividend00000111-3«1 = 600000110-3«0 = 300000011
Input:  a = 7, b = -3
Output: -2
Explanation: 7 / -3 = -2.333 truncates toward zero, giving -2.

Example 3

2824201612840dividend10000000000000000000000000000000-1«24 = 1677721600000001000000000000000000000000-1«23 = 838860800000000100000000000000000000000-1«22 = 419430400000000010000000000000000000000-1«21 = 209715200000000001000000000000000000000-1«20 = 104857600000000000100000000000000000000-1«19 = 52428800000000000010000000000000000000
Input:  a = -2147483648, b = -1
Output: 2147483647
Explanation: The true answer 2147483648 overflows, so it is clamped.

Constraints

  • -2^31 <= dividend, divisor <= 2^31 - 1
  • divisor != 0
Editorial — intuition, approach, complexity and pitfalls

Intuition

Repeated subtraction is correct but O(quotient), which is far too slow. Speed it up the way long division does: double the divisor until doubling once more would overshoot, subtract that large chunk, and record the matching power of two. Each round at least halves the remainder, so there are at most 32 rounds. Doubling is a left shift, so no multiplication is needed.

Approach

  1. Handle the single overflow case first: dividend == -2^31 and divisor == -1 returns 2^31 - 1.
  2. Record the sign of the result as (dividend < 0) != (divisor < 0), then work with magnitudes. Use a 64-bit or unsigned type so abs(-2^31) does not overflow.
  3. While the remainder is at least the divisor, find the largest k with divisor << k <= remainder by doubling.
  4. Subtract that chunk, add 1 << k to the quotient, and repeat with the new remainder.
  5. Apply the sign at the end.
class Solution:
    def divide(self, a, b):
        INT_MAX = 2**31 - 1
        if a == -2**31 and b == -1:
            return INT_MAX
        negative = (a < 0) != (b < 0)
        x, y = abs(a), abs(b)
        quotient = 0
        while x >= y:
            chunk, power = y, 1
            while x >= (chunk << 1):
                chunk <<= 1
                power <<= 1
            x -= chunk
            quotient += power
        return -quotient if negative else quotient

Dry Run

10 / 3, with no multiplication, division or modulo
  magnitudes 10 and 3, result is positive
  double 3 while it still fits: 3, then 6 (3 x 2); 12 would exceed 10, stop
     subtract 6, remainder 4, quotient so far 2
  double again from 3: 6 exceeds 4, so take 3 x 1
     subtract 3, remainder 1, quotient so far 3
answer 3
7 / -3
  magnitudes 7 and 3, result is negative
  3 doubles to 6, which fits; subtract it, remainder 1, quotient 2
  3 exceeds 1, so stop
answer -2    --  truncated toward zero, not toward negative infinity
Repeated doubling is what keeps this O(log n) rather than O(n). Subtracting the
divisor one at a time would take 2^31 steps in the worst case; doubling peels off
the largest power-of-two multiple each round, so there are at most 32 rounds.
The sign is handled by working on magnitudes and reapplying it at the end. That is
not tidiness -- in Python, -7 // 3 is -3 while this problem wants -2, so dividing
signed values would round the wrong way.
The -2^31 / -1 guard comes first because its true quotient, 2147483648, is the one
value that does not fit in a signed 32-bit int. Remove the guard and the function
returns exactly that, which overflows in every fixed-width language.
Two more traps worth naming: in Java and C++, Math.abs(Integer.MIN_VALUE) is still
negative, so widen to long before taking magnitudes. And the inner loop tests
x >= step << 1 BEFORE shifting, never after, so the shift never overflows.

Complexity

  • Time — O(log^2 n) in the worst case, and O(log n) if you shift down from a precomputed high bit.
  • Space — O(1).

Common Pitfalls

  • The overflow case is the actual point of this question. -2^31 / -1 is the only pair whose true quotient is unrepresentable - answer it before anything else.
  • Truncate toward zero, not toward negative infinity. In Python, -7 // 3 is -3, so compute on magnitudes and reapply the sign rather than dividing signed values.
  • In Java and C++, Math.abs(Integer.MIN_VALUE) is still negative. Widen to long before taking magnitudes.
  • Guard the inner doubling loop against overflow: check x >= chunk << 1 before shifting, never after.

Full Solution — all languages

class Solution:
    def divide(self, a, b):
        INT_MIN, INT_MAX = -2147483648, 2147483647
        if a == INT_MIN and b == -1:
            return INT_MAX
        negative = (a < 0) != (b < 0)
        x, y = abs(a), abs(b)
        out = 0
        while x >= y:
            step, count = y, 1
            while x >= (step << 1):
                step <<= 1
                count <<= 1
            x -= step
            out += count
        return -out if negative else out
Asked at Samsung
SensAI
Beta
Tap the mic to stop voice mode