Implement integer division without using division
Company: Amazon
Role: Applied Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: 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.
Read the full Amazon Applied Scientist interview experience this question came from
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.
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.