-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path338.counting-bits.py
More file actions
38 lines (30 loc) · 927 Bytes
/
338.counting-bits.py
File metadata and controls
38 lines (30 loc) · 927 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
36
37
38
# EASY
# first submission
# runtime: 65 ms O(n log n)
# memory: 23.31 MB
class Solution:
def countBits(self, n: int) -> List[int]:
counts = []
for num in range(0, n + 1):
counts.append(str(bin(num)).count('1'))
return counts
# second submission
# runtime: 228 ms O(n log n)
# memory: 23.17 MB
class Solution:
BITS = "01"
def countBits(self, n: int) -> List[int]:
counts = []
for num in range(0, n + 1):
counts.append(self.convert(num).count('1'))
return counts
def encode(self, n: int) -> str:
try:
return self.BITS[n]
except IndexError:
raise Exception("\ncannot encode: %s" % n)
def convert(self, decimal: int) -> str:
if decimal < 2:
return self.encode(decimal)
else:
return self.convert(decimal // 2) + self.encode(decimal % 2)