Divide Two Integers

medium

Given two integers dividend and divisor, divide them without using multiplication, division, or the modulo operator, and return the quotient after truncating toward zero (e.g. 8 / -3 = -2).

The result must fit in a signed 32-bit integer. If it would overflow — which happens only for -2^31 / -1 — return 2^31 - 1 instead.

Hints

Division is repeated subtraction — but subtracting one divisor at a time can take billions of steps.
Subtract in chunks: the largest doubling of the divisor (divisor, 2x, 4x, ...) that still fits.
Work in absolute values with a wide type, reapply the sign, and clamp the one overflow: -2^31 / -1.

Common doubts

Mathematically it's 2^31, but the largest signed 32-bit integer is 2^31 - 1. It's the only input pair that overflows, so it's clamped to 2^31 - 1.
abs(-2^31) is 2^31, which doesn't fit a 32-bit int. Promoting to 64-bit lets the magnitudes and doubled chunks be represented without overflow.
Yes — the ban is on *, /, and %. You can double with + or a left shift and halve with a right shift, as long as you respect each language's integer width.

Interview follow-ups

It falls out for free: whatever is left in a after the loop is |dividend| mod |divisor|; give it the dividend's sign for a truncated remainder.
Each chunk at least halves the remaining magnitude relative to plain subtraction, so the number of chunks is proportional to the number of bits in the quotient — logarithmic.

Fun facts

  • This is exactly how hardware does integer division: shift-and-subtract, one quotient bit at a time.
  • Doubling to build a product/quotient (instead of multiplying) is the same trick behind 'Russian peasant' multiplication.

Asked at

AmazonMicrosoftGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: dividend = 10, divisor = 3
Output: 3
10 / 3 = 3.333..., truncated toward zero to 3.
Example 2
Input: dividend = 7, divisor = -3
Output: -2
7 / -3 = -2.333..., truncated toward zero to -2.
Example 3
Input: dividend = -2147483648, divisor = -1
Output: 2147483647
The true result 2^31 overflows a signed 32-bit int, so it is clamped to 2^31 - 1.
Constraints

- -2^31 <= dividend, divisor <= 2^31 - 1 - divisor != 0 - The quotient is truncated toward zero.

Solve this problem →