Divide Two Integers
Medium
Topics
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
/: 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.Input: a = 10, b = 3 Output: 3 Explanation: 10 / 3 = 3.333 truncates to 3.
Example 2
Input: a = 7, b = -3 Output: -2 Explanation: 7 / -3 = -2.333 truncates toward zero, giving -2.
Example 3
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
- Handle the single overflow case first:
dividend == -2^31anddivisor == -1returns2^31 - 1. - Record the sign of the result as
(dividend < 0) != (divisor < 0), then work with magnitudes. Use a 64-bit or unsigned type soabs(-2^31)does not overflow. - While the remainder is at least the divisor, find the largest
kwithdivisor << k <= remainderby doubling. - Subtract that chunk, add
1 << kto the quotient, and repeat with the new remainder. - 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 quotientDry 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 / -1is the only pair whose true quotient is unrepresentable - answer it before anything else. - Truncate toward zero, not toward negative infinity. In Python,
-7 // 3is-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 tolongbefore taking magnitudes. - Guard the inner doubling loop against overflow: check
x >= chunk << 1before 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 outimport java.util.*;
class Solution {
public int divide(int a, int b) {
if (a == Integer.MIN_VALUE && b == -1) return Integer.MAX_VALUE;
boolean negative = (a < 0) != (b < 0);
long x = Math.abs((long) a), y = Math.abs((long) b), out = 0;
while (x >= y) {
long step = y, count = 1;
while (x >= (step << 1)) {
step <<= 1;
count <<= 1;
}
x -= step;
out += count;
}
return (int) (negative ? -out : out);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int divide(int a, int b) {
const long long INT_MIN_V = -2147483648LL, INT_MAX_V = 2147483647LL;
if (a == INT_MIN_V && b == -1) return (int)INT_MAX_V;
bool negative = (a < 0) != (b < 0);
long long x = llabs((long long)a), y = llabs((long long)b), out = 0;
while (x >= y) {
long long step = y, count = 1;
while (x >= (step << 1)) {
step <<= 1;
count <<= 1;
}
x -= step;
out += count;
}
return (int)(negative ? -out : out);
}
};/**
* @param {number} a
* @param {number} b
* @return {number}
*/ var divide = function(a, b) {
const INT_MIN = -2147483648, INT_MAX = 2147483647;
if (a === INT_MIN && b === -1) return INT_MAX;
const negative = (a < 0) !== (b < 0);
let x = Math.abs(a), y = Math.abs(b), out = 0;
while (x >= y) {
let step = y, count = 1;
// doubling by addition: << would truncate to 32 bits and * is forbidden here
while (x >= step + step) {
step += step;
count += count;
}
x -= step;
out += count;
}
return negative ? -out : out;
};