Skip to content

Commit 5e56791

Browse files
1017 Convert to Base -2.py
1 parent 070825f commit 5e56791

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

1017 Convert to Base -2.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a number N, return a string consisting of "0"s and "1"s that represents
4+
its value in base -2 (negative two).
5+
6+
The returned string must have no leading zeroes, unless the string is "0".
7+
8+
9+
10+
Example 1:
11+
12+
Input: 2
13+
Output: "110"
14+
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
15+
Example 2:
16+
17+
Input: 3
18+
Output: "111"
19+
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
20+
Example 3:
21+
22+
Input: 4
23+
Output: "100"
24+
Explantion: (-2) ^ 2 = 4
25+
26+
27+
Note:
28+
0 <= N <= 10^9
29+
"""
30+
from collections import deque
31+
32+
33+
class Solution:
34+
def baseNeg2(self, N: int) -> str:
35+
"""
36+
% -2, // -2 ? not really
37+
38+
alternating
39+
40+
41+
3
42+
(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0, LSB set
43+
minus reminder, divide by -2
44+
(-2) ^ 1 + (-2) ^ 0, LSB set
45+
minus reminder, divide by -2
46+
(-2) ^ 0, LSB set
47+
48+
4
49+
(-2) ^ 2 + 0 ^ 1 + 0 ^ 0, LSB not set
50+
minus reminder, divide by -2
51+
(-2) ^ 1 + 0 ^ 0, LSB not set
52+
minus reminder, divide by -2
53+
(-2) ^ 0, LSB set
54+
"""
55+
ret = deque()
56+
while N != 0:
57+
r = N % 2 # r is the range of 0 and 2
58+
ret.appendleft(r)
59+
N -= r
60+
N //= -2
61+
62+
return "".join(map(str, ret)) or "0"
63+
64+
65+
if __name__ == "__main__":
66+
assert Solution().baseNeg2(3) == "111"
67+
assert Solution().baseNeg2(4) == "100"

0 commit comments

Comments
 (0)