Problem statement

https://leetcode.com/problems/convert-to-base-2/

Solution

Actually not difficult problem, all we need to do is to apply usual algorithm for base 2, but for -2: it will work here.

Complexity

It is O(log n) for time and space.

Code

class Solution:
    def baseNeg2(self, n):
        if n == 0: return "0"
        ans = []
        while n != 0:
            ans += [n % 2]
            n = (n - ans[-1])//(-2)
        
        return "".join(str(i) for i in ans[::-1])