29. Divide Two Integers
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core task is to implement integer division using only addition, subtraction, and bitwise operations, without using multiplication, division, or the modulo operator. The main challenges are handling integer overflow, especially with the 32-bit signed integer limits ([-2^31, 2^31 - 1]), and achieving a solution that is efficient enough to pass within the time limits, as a naive repeated subtraction approach would be too slow.
Solution
Divide Two Integers in Python
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
# Define 32-bit integer limits for clarity and correctness
INT_MAX = 2**31 - 1
INT_MIN = -2**31
# Handle the overflow case where dividend is INT_MIN and divisor is -1
if dividend == INT_MIN and divisor == -1:
return INT_MAX
# Determine the sign of the quotient. XOR is true if signs are different.
is_negative = (dividend < 0) ^ (divisor < 0)
# Work with absolute values. Python's integers have arbitrary precision,
# so abs(INT_MIN) is not an issue.
abs_dividend = abs(dividend)
abs_divisor = abs(divisor)
quotient = 0
# Main logic: repeatedly subtract multiples of the divisor
while abs_dividend >= abs_divisor:
# Find the largest multiple of abs_divisor (in the form of abs_divisor * 2^k)
# that is less than or equal to abs_dividend
temp_divisor = abs_divisor
multiple = 1
# Use left shift to find the largest power-of-2 multiple
while abs_dividend >= (temp_divisor << 1):
temp_divisor <<= 1
multiple <<= 1
# Subtract the found multiple from the dividend
abs_dividend -= temp_divisor
# Add the corresponding multiple to the quotient
quotient += multiple
# Apply the sign to the result
if is_negative:
quotient = -quotient
# After handling the overflow case, the result is guaranteed to be within the 32-bit range.
return quotient
Divide Two Integers in Java
class Solution {
public int divide(int dividend, int divisor) {
// Handle the specific overflow case as per problem description.
// Math.pow(2, 31) overflows int, so it should be clamped to Integer.MAX_VALUE.
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
// Use long to handle Math.abs(Integer.MIN_VALUE) without overflow.
long absDividend = Math.abs((long) dividend);
long absDivisor = Math.abs((long) divisor);
// Determine the sign of the quotient.
// XOR is true if signs are different.
boolean isNegative = (dividend < 0) ^ (divisor < 0);
long quotient = 0;
// Repeatedly subtract multiples of the divisor.
while (absDividend >= absDivisor) {
// Find the largest multiple of absDivisor (in the form of absDivisor * 2^k)
// that is less than or equal to absDividend.
long tempDivisor = absDivisor;
long multiple = 1;
// Use left shift to find the largest power-of-2 multiple.
// We check (tempDivisor << 1) to ensure the next multiple won't exceed absDividend.
while (absDividend >= (tempDivisor << 1)) {
tempDivisor <<= 1;
multiple <<= 1;
}
// Subtract the found multiple from the dividend.
absDividend -= tempDivisor;
// Add the corresponding multiple to the quotient.
quotient += multiple;
}
// Apply the sign.
if (isNegative) {
quotient = -quotient;
}
// The result is guaranteed to be within the 32-bit integer range
// because the only overflow case was handled at the beginning.
return (int) quotient;
}
}
Divide Two Integers in C++
class Solution {
public:
int divide(int dividend, int divisor) {
// Handle the only overflow case as per the problem description.
// The mathematical result is 2^31, which overflows a 32-bit signed integer.
if (dividend == INT_MIN && divisor == -1) {
return INT_MAX;
}
// Use long long to handle the absolute value of INT_MIN without overflow.
long long ldividend = std::abs((long long)dividend);
long long ldivisor = std::abs((long long)divisor);
// Determine the sign of the quotient.
bool is_negative = (dividend < 0) ^ (divisor < 0);
long long quotient = 0;
// The main logic: repeatedly subtract multiples of the divisor.
while (ldividend >= ldivisor) {
// Find the largest multiple of ldivisor (in the form of ldivisor * 2^k)
// that is less than or equal to ldividend.
long long temp_divisor = ldivisor;
long long multiple = 1;
// Use left shift to find the largest power-of-2 multiple.
// We check (temp_divisor << 1) to ensure the next multiple won't exceed ldividend.
// The check must be against ldividend to prevent temp_divisor from overflowing itself if ldividend is very large,
// though `long long` gives us a large headroom.
while (ldividend >= (temp_divisor << 1)) {
temp_divisor <<= 1;
multiple <<= 1;
}
// Subtract the found multiple from the dividend.
ldividend -= temp_divisor;
// Add the corresponding multiple to the quotient.
quotient += multiple;
}
// Apply the sign to the result.
if (is_negative) {
quotient = -quotient;
}
// The result is guaranteed to be within the 32-bit integer range
// because we handled the INT_MIN / -1 case at the beginning.
return (int)quotient;
}
};
Divide Two Integers in TypeScript
function divide(dividend: number, divisor: number): number {
const INT_MAX = 2**31 - 1;
const INT_MIN = -(2**31);
// Handle the specific overflow case.
if (dividend === INT_MIN && divisor === -1) {
return INT_MAX;
}
// Determine sign. `!=` acts as XOR for booleans.
const isNegative = (dividend < 0) !== (divisor < 0);
// Work with absolute values.
// Math.abs() works fine for all numbers up to Number.MAX_SAFE_INTEGER.
let absDividend = Math.abs(dividend);
let absDivisor = Math.abs(divisor);
let quotient = 0;
while (absDividend >= absDivisor) {
let tempDivisor = absDivisor;
let multiple = 1;
// Find the largest power-of-2 multiple.
// In JS/TS, bitwise operators work on 32-bit signed ints.
// Shifting a large number can lead to unexpected behavior due to it being cast to 32 bits.
// e.g. (2**30 << 1) becomes -2**31.
// Using addition `tempDivisor + tempDivisor` is safer and equivalent to `tempDivisor << 1` for positive numbers.
while (absDividend >= (tempDivisor + tempDivisor)) {
// JS numbers are 64-bit floats, so addition is safe for integers up to 2**53.
tempDivisor += tempDivisor;
multiple += multiple;
}
absDividend -= tempDivisor;
quotient += multiple;
}
// Apply sign.
if (isNegative) {
quotient = -quotient;
}
// The problem statement guarantees inputs are within 32-bit range, and we've handled the
// single overflow case. The result will be within the valid range.
return quotient;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.