Implement integer division without using division
Company: Amazon
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in implementing low-level integer arithmetic and algorithmic optimization, including correct handling of overflow and edge cases within 32-bit signed integer constraints.
Constraints
- -2^31 <= dividend <= 2^31 - 1
- -2^31 <= divisor <= 2^31 - 1
- divisor != 0
- Do not use multiplication (*), division (/), or modulo (%) operators
- The algorithm should be better than O(|dividend|)
Examples
Input: (10, 3)
Expected Output: 3
Explanation: 10 divided by 3 is 3.333..., which truncates toward zero to 3.
Input: (7, -3)
Expected Output: -2
Explanation: 7 divided by -3 is -2.333..., which truncates toward zero to -2.
Input: (-15, 4)
Expected Output: -3
Explanation: -15 divided by 4 is -3.75, which truncates toward zero to -3.
Input: (0, 5)
Expected Output: 0
Explanation: Zero divided by any nonzero integer is 0.
Input: (-2147483648, -1)
Expected Output: 2147483647
Explanation: The mathematical result is 2147483648, which exceeds the maximum 32-bit signed integer, so the result is clamped to 2147483647.
Input: (-2147483648, 1)
Expected Output: -2147483648
Explanation: The quotient is exactly the minimum 32-bit signed integer, so it is returned unchanged.
Solution
def solution(dividend, divisor):
INT_MIN = -(1 << 31)
INT_MAX = (1 << 31) - 1
# The only overflow case for 32-bit signed integer division.
if dividend == INT_MIN and divisor == -1:
return INT_MAX
# Determine whether the final result should be negative.
negative = (dividend < 0) != (divisor < 0)
# Work with positive magnitudes. Python can safely represent abs(INT_MIN).
a = -dividend if dividend < 0 else dividend
b = -divisor if divisor < 0 else divisor
quotient = 0
# Build the quotient from high powers of two down to low powers of two.
# Since inputs are 32-bit, checking shifts from 31 down to 0 is enough.
for shift in range(31, -1, -1):
shifted = b << shift
if shifted <= a:
a -= shifted
quotient += 1 << shift
if negative:
quotient = -quotient
if quotient < INT_MIN:
return INT_MIN
if quotient > INT_MAX:
return INT_MAX
return quotientTime complexity: O(log |dividend|), which is at most 32 iterations for 32-bit integers. Space complexity: O(1).
Hints
- Instead of subtracting the divisor one time at a time, try subtracting the largest doubled version of the divisor that fits into the remaining dividend.
- Bit shifts can be used to efficiently double numbers and build the quotient from powers of two.