Leetcode 1070 Solution

This article provides solution to leetcode question 1070 (convert-to-base-2)

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

Solution

class Solution:
    def baseNeg2(self, N: int) -> str:
        if N == 0:
            return "0"

        ans = []
        while N:
            if len(ans) % 2 == 0:
                ans.append(str(N % 2))
                N //= 2
            else:
                ans.append(str((-N) % 2))
                N = -((-N) // 2)

        return "".join(reversed(ans))