1017. Convert to Base -2
- Convert to Base -2 python solution
题目描述
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).
The returned string must have no leading zeroes, unless the string is “0”.
解析
负2进制的原理如下图所示
class Solution:
def baseNeg2(self, N: int) -> str:
res=[]
while N:
res.append(N&1)
N=-(N>>1)
return "".join(map(str,res[::-1] or [0]))
Reference
https://leetcode.com/problems/convert-to-base-2/discuss/265507/JavaC%2B%2BPython-2-lines-Exactly-Same-as-Base-2