Divide Two Integers (LeetCode 29): Solution and Explanation
Return dividend / divisor truncated toward zero, without using multiplication, division or mod. Results outside the signed 32-bit range clamp to 2^31 - 1 or -2^31.
Intuition
Division asks how many copies of the divisor fit inside the dividend. Subtracting one copy at a time answers that, but 2147483647 / 1 would take two billion loop turns.
Long division from school is faster because it subtracts big chunks first: hundreds of copies, then tens, then ones. In binary the chunks are the divisor times a power of two, and a left shift makes them for free: b << i is b * 2^i.
So walk i from 31 down to 0. Whenever b << i still fits in what is left of the dividend, subtract it and set bit i of the quotient. Each bit is decided exactly once, so the loop has 32 turns no matter how big the numbers are.
Signs and overflow are bookkeeping. Divide the absolute values, make the result negative when exactly one input is negative, and catch INT_MIN / -1 up front, because the true answer 2147483648 does not fit in 32 bits.
Approach: Binary long division with shifts
- If
dividendisINT_MINanddivisoris-1, returnINT_MAX. - Set
negativeto true when exactly one of the two inputs is negative. - Let
a = |dividend|andb = |divisor|, stored in a 64-bit type so|INT_MIN|fits. - For
ifrom 31 down to 0: if(a >> i) >= b, thenb << ifits ina. Subtract it fromaand add1 << ito the quotient. - Return
-quotientifnegative, otherwisequotient.
Step-by-step example
dividend = 10, divisor = 3
- Not the overflow case. Both inputs are positive, so the answer is non-negative. a = 10, b = 3.
- For i from 31 down to 2,
a >> iis smaller than 3, so those quotient bits are 0. - i = 1:
b << 1= 6 fits in 10. Subtract it: a = 4. Set bit 1: quotient = 2. - i = 0:
b << 0= 3 fits in 4. Subtract it: a = 1. Set bit 0: quotient = 3. - The remainder 1 is smaller than 3, the loop is over, and the function returns 3.
Code: Python, Java, C++
1class Solution:
2 def divide(self, dividend: int, divisor: int) -> int:
3 INT_MAX, INT_MIN = 2**31 - 1, -(2**31)
4 if dividend == INT_MIN and divisor == -1:
5 return INT_MAX
6 negative = (dividend < 0) != (divisor < 0)
7 a, b = abs(dividend), abs(divisor)
8 quotient = 0
9 for i in range(31, -1, -1):
10 if (a >> i) >= b:
11 a -= b << i
12 quotient += 1 << i
13 return -quotient if negative else quotient1class Solution {
2 public int divide(int dividend, int divisor) {
3 if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
4 boolean negative = (dividend < 0) != (divisor < 0);
5 long a = Math.abs((long) dividend), b = Math.abs((long) divisor);
6 long quotient = 0;
7 for (int i = 31; i >= 0; i--) {
8 if ((a >> i) >= b) {
9 a -= b << i;
10 quotient += 1L << i;
11 }
12 }
13 return (int) (negative ? -quotient : quotient);
14 }
15}1class Solution {
2public:
3 int divide(int dividend, int divisor) {
4 if (dividend == INT_MIN && divisor == -1) return INT_MAX;
5 bool negative = (dividend < 0) != (divisor < 0);
6 long long a = llabs((long long) dividend), b = llabs((long long) divisor);
7 long long quotient = 0;
8 for (int i = 31; i >= 0; i--) {
9 if ((a >> i) >= b) {
10 a -= b << i;
11 quotient += 1LL << i;
12 }
13 }
14 return (int) (negative ? -quotient : quotient);
15 }
16};Time and space complexity
O(log n)
The loop decides one quotient bit per turn, and a 32-bit quotient has at most 32 bits. That is constant for fixed-width integers.
O(1)
A few integer variables, no arrays and no recursion.
Other approaches
Repeated subtraction (time O(n), space O(1))
Subtract the divisor until the dividend goes below it and count the turns. Simple and correct, but it times out when the quotient is in the billions.
Repeated doubling (time O(log^2 n), space O(1))
Each round, double a copy of the divisor until the next doubling would overshoot, subtract that chunk, and start doubling again from the divisor. It avoids fixed bit positions but redoes the doubling every round.
Negative-range arithmetic (time O(log n), space O(1))
Convert both numbers to negatives instead of positives, since the negative range is one larger than the positive one. This keeps everything in 32 bits when a 64-bit type is not allowed, at the cost of trickier comparisons.
Common mistakes
- Forgetting
INT_MIN / -1. The exact answer is 2147483648, which overflows a 32-bit int, and in some languages the division itself crashes. - Taking
abs(INT_MIN)in a 32-bit int. It stays negative in Java, C++ and C#, so widen to 64 bits first. - Testing
(b << i) <= adirectly. The shift can overflow;(a >> i) >= basks the same question safely. - Rounding toward negative infinity instead of toward zero. -7 / 2 must be -3, not -4, which is why the sign is applied after dividing the absolute values.
Frequently asked questions
Why does the loop start at i = 31?
The absolute value of a 32-bit integer is at most 2^31, so no quotient can have a bit above position 31. Starting there covers every possible answer.
Is using a 64-bit long allowed?
LeetCode accepts it, and most solutions use one for the absolute values. If you want to stay strictly in 32 bits, work with negative numbers instead, since -2^31 has no positive counterpart.
Why is INT_MIN / -1 the only overflow case?
Dividing by any other divisor makes the magnitude no larger than the dividend's, and every 32-bit value except INT_MIN has a 32-bit negation. Only INT_MIN negated, 2^31, falls outside the range.
How is this related to long division?
It is long division in base 2. Each step asks whether the divisor times the current place value fits, writes a 1 or a 0, and carries the remainder to the next lower place.