Contest 130 - Prob2 Convert to Base -2

Python Recursion with Detailed Explanations
This is similar to how we convert a decimal number to its binary form. A simple example is when N = 9. The following is how we convert 9 to 1001 with the base of 2.
9 = 2 * 4 + 1
4 = 2 * 2 + 0
2 = 2 * 1 + 0
1 = 2 * 0 + 1
Each time we decompose a number using N = 2 * q + r, it's like doing bin(N) = bin(q) + str(r). Reversely (from the bottom-up perspective), 1 is 0b1; 2 is 0b10; 4 is 0b100; 9 is 0b1001.
When the base is -2, it is the same logic.
9 = -2 * -4 + 1
-4 = -2 * 2 + 0
2 = -2 * -1 + 0
-1 = -2 * 1 + 1
1 = -2 * 0 + 1
Therefore, 9 is converted to 11001, the reverse of 10011.

class Solution:
    def baseNeg2(self, N: int) -> str:
        if N in [0, 1]: return str(N)
        if N % 2 == 0:
            return self.baseNeg2(N // -2) + '0'
        else:
            return self.baseNeg2((N - 1) // -2) + '1'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,553评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,026评论 0 38
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 6,135评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 6,949评论 0 2