# 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阅读 8,722评论 0 13
• rljs by sennchi Timeline of History Part One The Cognitiv...
sennchi阅读 5,459评论 0 10
• Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
苏黎九歌阅读 12,538评论 0 39
• Substrate的transaction-payment模块分析 transaction-payment模块提供...
建怀阅读 6,426评论 0 4
• 16宿命：用概率思维提高你的胜算 以前的我是风险厌恶者，不喜欢去冒险，但是人生放弃了冒险，也就放弃了无数的可能。 ...
yichen大刀阅读 4,247评论 0 3
• 公元：2019年11月28日19时42分农历：二零一九年 十一月 初三日 戌时干支：己亥乙亥己巳甲戌当月节气：立冬...
石放阅读 5,450评论 0 2