Convert to Base -2 Problem
Description
LeetCode Problem 1017.
Given an integer n, return a binary string representing its representation in base -2.
Note that the returned string should not have leading zeros unless the string is "0".
Example 1:
Input: n = 2
Output: "110"
Explantion: (-2)^2 + (-2)^1 = 2
Example 2:
Input: n = 3
Output: "111"
Explantion: (-2)^2 + (-2)^1 + (-2)^0 = 3
Example 3:
Input: n = 4
Output: "100"
Explantion: (-2)^2 = 4
Constraints:
0 <= n <= 10^9
Solution
Approach: Repeated Division by -2
In base -2, n = d0 + d1 * (-2) + d2 * (-2)^2 + ... with every digit d equal to 0 or 1. Everything after d0 is a multiple of 2, so the last digit d0 is just the parity of n, as in ordinary binary: d0 = n & 1.
Remove that digit, and what is left is (-2) * (d1 + d2 * (-2) + ...). So the remaining digits are the base -2 digits of (n - d0) / -2, and we repeat until the number becomes 0. The division is exact because n - d0 is even, so we do not have to worry about how each language rounds negative numbers. The parity test n & 1 also works for negative values, which do show up along the way: for n = 2 we get digit 0, then n = -1, digit 1, then n = 1, digit 1, then n = 0, so 2 is "110".
The digits come out from the least significant one, so we reverse them at the end. n = 0 produces no digits at all, so it is handled first and returns "0".
Complexity: O(log n) time and O(log n) space for the digits.
class Solution:
def baseNeg2(self, n: int) -> str:
if n == 0:
return "0"
digits = [] # least significant first
while n != 0:
bit = n & 1 # the last digit is n's parity, as in base 2
digits.append(str(bit))
n = (n - bit) // -2 # exact: n - bit is even
return "".join(reversed(digits))