Description
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”.
Example 1:
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
Example 2:
Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
Example 3:
Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4
Note:
- 0 <= N <= 10^9
分析
题目的意思是:给定数N,转换成-2进制的数。这道题我用转换成2进制的思路做了一下,发现行不通。第一个解法按照位运算的解法是我参考的别人的,比较难理解,我只理解2进制的情况;另一个解法是常规的转换,写法有点新颖,学习一下。
代码
class Solution:
def baseNeg2(self, N: int) -> str:
res=[]
while(N!=0):
res.append(str(N&1))
N=-(N>>1)
if(len(res)>0):
res.reverse()
return ''.join(res)
return '0'
class Solution:
def baseNeg2(self, N: int) -> str:
res=[]
while(N!=0):
res.append(str(N&1))
if(N%2==1):
N-=1
N=N//(-2)
if(len(res)>0):
res.reverse()
return ''.join(res)
return '0'
参考文献
1017. Convert to Base -2
【LeetCode】 1017. Convert to Base -2 (Part 1)