Magicsheet logo

Convert to Base -2

Medium
70.4%
Updated 6/1/2025

Asked by 2 Companies

Topics

Convert to Base -2

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

This follows the standard Math interview pattern for base conversion, with a slight modification.

  1. Repeatedly divide the number by the base (-2).
  2. Calculate the remainder.
  3. Crucial Step: In many languages, 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.
  4. Store the remainders and reverse them at the end.

Example explanation

Input: N = 3

  1. 3 / -2 = -1, remainder 1. (3 = -2 * -1 + 1). Result: [1].
  2. -1 / -2 = 1, remainder 1. (-1 = -2 * 1 + 1). Result: [1, 1].
  3. 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!

Common mistakes candidates make

  • Negative Remainders: Forgetting that digits in a base system cannot be negative.
  • Base Case: Not handling the case where the input N is 0 (should return "0").
  • Infinite Loops: Not properly updating the quotient, leading to a loop that never reaches zero.

Interview preparation tip

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.

Similar Questions