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
本文介绍了一种将十进制数转换为负2进制表示的算法,使用Python实现。通过位运算,该方法能高效地进行转换,避免了传统正进制转换的繁琐步骤。
482

被折叠的 条评论
为什么被折叠?



