Skip to content

Latest commit

 

History

History
23 lines (21 loc) · 479 Bytes

1017.md

File metadata and controls

23 lines (21 loc) · 479 Bytes

1017. Convert to Base -2

Solution 1 (time O(logn), space O(1))

class Solution(object):
    def baseNeg2(self, n):
        """
        :type n: int
        :rtype: str
        """
        k = 1
        ans = []
        while n:
            if n % 2:
                ans.append("1")
                n -= k
            else:
                ans.append("0")
            n //= 2
            k *= -1
        return "".join(ans[::-1]) or "0"