LeetCode solutions

1070. Convert to Base -2

My accepted Python solution to LeetCode problem 1070, Convert to Base -2, running in 2ms.

  • Difficulty: Medium
  • Python
  • Runtime 2ms
  • Memory 17.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 2ms, memory 17.5MB, accepted 2026-01-02.

python
class Solution:
    def baseNeg2(self, n: int) -> str:
        if n == 0:
            return "0"
        
        result = []
        while n != 0:
            remainder = n % (-2)
            n //= -2
            
            # Handle negative remainder
            if remainder < 0:
                remainder += 2
                n += 1
            
            result.append(str(remainder))
        
        return ''.join(result[::-1])

Source