forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert-to-base-2.py
More file actions
35 lines (32 loc) · 767 Bytes
/
convert-to-base-2.py
File metadata and controls
35 lines (32 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Time: O(logn)
# Space: O(1)
class Solution(object):
def baseNeg2(self, N):
"""
:type N: int
:rtype: str
"""
result = []
while N:
result.append(str(-N & 1)) # N % -2
N = -(N >> 1) # N //= -2
result.reverse()
return "".join(result) if result else "0"
# Time: O(logn)
# Space: O(1)
class Solution2(object):
def baseNeg2(self, N):
"""
:type N: int
:rtype: str
"""
BASE = -2
result = []
while N:
N, r = divmod(N, BASE)
if r < 0:
r -= BASE
N += 1
result.append(str(r))
result.reverse()
return "".join(result) if result else "0"