Convert to Base -2 - Problem

In the fascinating world of number systems, we typically work with positive bases like binary (base 2) or decimal (base 10). But what happens when we venture into negative bases?

Your mission: Given an integer n, convert it to its representation in base -2 and return it as a binary string. In base -2, each position represents a power of -2 instead of 2:

  • Position 0: (-2)0 = 1
  • Position 1: (-2)1 = -2
  • Position 2: (-2)2 = 4
  • Position 3: (-2)3 = -8
  • And so on...

Important: The result should not have leading zeros unless the answer is exactly "0".

Example: The number 2 in base -2 is "110" because: 1×4 + 1×(-2) + 0×1 = 4 - 2 + 0 = 2

Input & Output

example_1.py — Simple Positive Number
$ Input: n = 2
Output: "110"
💡 Note: In base -2: 1×(-2)² + 1×(-2)¹ + 0×(-2)⁰ = 1×4 + 1×(-2) + 0×1 = 4 - 2 + 0 = 2
example_2.py — Negative Number
$ Input: n = -3
Output: "1011"
💡 Note: In base -2: 1×(-2)³ + 0×(-2)² + 1×(-2)¹ + 1×(-2)⁰ = 1×(-8) + 0×4 + 1×(-2) + 1×1 = -8 + 0 - 2 + 1 = -9 + 6 = -3
example_3.py — Edge Case Zero
$ Input: n = 0
Output: "0"
💡 Note: Zero is represented as "0" in any base system

Constraints

  • -106 ≤ n ≤ 106
  • The result should not have leading zeros except when the answer is "0"
  • Note: Base -2 can represent both positive and negative integers using only digits 0 and 1

Visualization

Tap to expand
Base -2: The Alternating Credit-Debt System-8Position 3+4Position 2-2Position 1+1Position 0Example: Convert 2 to Base -20110Calculation: 0×(-8) + 1×4 + 1×(-2) + 0×1 = 0 + 4 - 2 + 0 = 2Division Algorithm Steps:1. n=2: 2÷(-2)=-1 remainder 0 → digit 02. n=-1: -1÷(-2)=0 remainder -1 → adjust to remainder 1, n=0 → digit 13. Continue with adjusted quotient until n=0110Final Answer
Understanding the Visualization
1
Set up the columns
Each position alternates between positive and negative values
2
Apply division algorithm
Divide by -2 and handle negative remainders
3
Build result
Collect digits from right to left to form the final answer
Key Takeaway
🎯 Key Insight: Base -2 conversion requires careful handling of negative remainders by adjusting both the remainder (+2) and quotient (+1) to maintain the binary digit constraint.
Asked in
Google 25 Microsoft 15 Amazon 12 Apple 8
24.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen