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 INPUT n = 2 (decimal integer) Binary (base 2): 10 Base -2 uses: (-2)^0 = 1 (-2)^1 = -2 (-2)^2 = 4 (-2)^3 = -8 Alternating signs! ALGORITHM STEPS 1 Initialize result = "", n = 2 2 Loop: n != 0 remainder = n % 2 3 Handle negative n = -(n / 2) 4 Build result Prepend remainder Iteration Trace n rem next n result 2 0 -1 "0" -1 1 1 "10" 1 1 0 "110" FINAL RESULT Output: "110" Verification: 1 * (-2)^2 = 1 * 4 = 4 1 * (-2)^1 = 1 * -2 = -2 0 * (-2)^0 = 0 * 1 = 0 Total: 4 + (-2) + 0 = 2 OK - Correct! Position: 2 1 0 Bits: 1 1 0 Key Insight: Unlike regular binary, base -2 uses negative powers for odd positions. The key trick is to negate the quotient after division: n = -(n / 2). This handles the alternating signs automatically, allowing us to represent any integer (positive or negative) without a sign bit! TutorialsPoint - Convert to Base -2 | Iterative Conversion Approach
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