[leetcode] 1017. Convert to Base -2

网友投稿 308 2022-08-26

[leetcode] 1017. Convert to Base -2

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: 2Output: "110"Explantion: (-2) ^ 2 + (-2) ^ 1 = 2

Example 2:

Input: 3Output: "111"Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3

Example 3:

Input: 4Output: "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)​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:从2021年爆款案例,看2022年营销趋势!(2021营销发展趋势)
下一篇:[leetcode] 1073. Adding Two Negabinary Numbers
相关文章

 发表评论

暂时没有评论,来抢沙发吧~