The Convert to Base -2 interview question asks you to represent a given integer N in base -2 (negabinary). In a standard binary system (base 2), each digit represents a power of 2 (1, 2, 4, 8, ...). In base -2, each digit represents a power of -2 (1, -2, 4, -8, ...). The digits allowed are still only 0 and 1. This system is interesting because it can represent both positive and negative integers without a separate sign bit.
Airbnb and Boeing use the Convert to Base -2 coding problem to test a candidate's grasp of number systems and modular arithmetic. It’s a "Medium" problem that requires you to adapt a familiar algorithm (base conversion) to an unfamiliar setting. It evaluates whether you can handle the mathematical edge cases that arise when the divisor is negative, particularly concerning how remainders are calculated in different programming languages.
This follows the standard Math interview pattern for base conversion, with a slight modification.
n % -2 can return -1. Since base digits must be 0 or 1, if the remainder is -1, you must adjust it to 1 and increment the quotient by 1.Input: N = 3
3 / -2 = -1, remainder 1. (3 = -2 * -1 + 1). Result: [1].-1 / -2 = 1, remainder 1. (-1 = -2 * 1 + 1). Result: [1, 1].1 / -2 = 0, remainder 1. (1 = -2 * 0 + 1). Result: [1, 1, 1].
Reverse [1, 1, 1] to get "111".
Check: 1*(-2)^2 + 1*(-2)^1 + 1*(-2)^0 = 4 - 2 + 1 = 3. Correct!N is 0 (should return "0").Always verify your language's behavior for the modulo operator with negative numbers. If (-1 % -2) gives -1, you need to manually adjust it to 1 to keep your base digits valid.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Alice and Bob Playing Flower Game | Medium | Solve | |
| Angle Between Hands of a Clock | Medium | Solve | |
| Check if Number is a Sum of Powers of Three | Medium | Solve | |
| Closest Divisors | Medium | Solve | |
| Count Total Number of Colored Cells | Medium | Solve |