Convert to Base -2 - Problem

Given an integer n, return a binary string representing its representation in base -2.

Note: The returned string should not have leading zeros unless the string is "0".

Input & Output

Example 1 — Positive Number
$ Input: n = 2
Output: "110"
💡 Note: 2 in base -2: 1×(-2)² + 1×(-2)¹ + 0×(-2)⁰ = 4 + (-2) + 0 = 2
Example 2 — Negative Number
$ Input: n = 3
Output: "111"
💡 Note: 3 in base -2: 1×(-2)² + 1×(-2)¹ + 1×(-2)⁰ = 4 + (-2) + 1 = 3
Example 3 — Edge Case Zero
$ Input: n = 0
Output: "0"
💡 Note: Zero is represented as "0" in any base system

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Convert to Base -2: Understanding the ProcessInputn = 2DecimalProcessBase -2DivisionAlgorithmOutput"110"Base -2 StringVerification:"110" in base -2 = 1×(-2)² + 1×(-2)¹ + 0×(-2)⁰= 1×4 + 1×(-2) + 0×1 = 4 - 2 + 0 = 2 ✓
Understanding the Visualization
1
Input
Decimal number n = 2
2
Process
Convert using base -2 arithmetic
3
Output
Binary string "110"
Key Takeaway
🎯 Key Insight: In base -2, handle negative remainders by adding the base magnitude and adjusting the quotient
Asked in
Google 15 Facebook 12
12.0K Views
Medium Frequency
~15 min Avg. Time
428 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