← Questions
Divide two integers without division
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Dec 2025. It tests bit manipulation and math.
Divide two 32-bit signed integers and return the quotient truncated toward zero, without using the multiplication, division or modulo operators. Subtracting the divisor one copy at a time is too slow; do better than O(|dividend|).
Interface
Unless you agree on a different interface with the interviewer, assume:
-
divide(dividend: int, divisor: int) -> int— if the true quotient is above2^31 - 1, return2^31 - 1.
Example
divide(10, 3) -> 3 # 3.33 truncated
divide(7, -3) -> -2 # -2.33 truncated toward zero, not -3
divide(-2147483648, -1) -> 2147483647 # 2^31 does not fit, so clamp
divide(-2147483648, 1) -> -2147483648
divide(1, 2) -> 0
Constraints
-
-2^31 <= dividend, divisor <= 2^31 - 1;divisor != 0. - Assume the environment holds only 32-bit signed integers if you are using a fixed-width language.
Clarifying questions
- Are bit shifts allowed? (Yes.)
- Can I use 64-bit integers internally?
- What should overflow return? (
2^31 - 1.)
What a strong answer covers
- Long division in binary: for shifts from 31 down to 0, if
divisor << sfits into what is left of the dividend, subtract it and add1 << sto the quotient. O(32) steps, or O(log² n) with repeated doubling. - Signs handled once: work with magnitudes and apply the sign at the end, or work in negative numbers so
-2^31never has to be negated in 32 bits. - The one overflow case,
-2^31 / -1, and shifts that would overflow the divisor. - Tests: signs in all four combinations, divisor 1 and -1, dividend 0,
|dividend| < |divisor|, the extreme values.
Follow-ups
- Return the remainder as well, with the sign rule of truncated division.
- Do it without 64-bit integers.
- How does hardware divide? Compare with this method.
Where it's asked
- Amazon · Coding · Last asked Dec 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
bit manipulation · math
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
