Skip to content

Commit 63a05ff

Browse files
committed
[LC] feat: 240824 counting bits
1 parent ec8bc19 commit 63a05ff

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

counting-bits/hajunyoo.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution1:
2+
# time complexity: O(n)
3+
# space complexity: O(1)
4+
def countBits(self, n: int) -> List[int]:
5+
list = [i for i in range(n + 1)]
6+
result = [bin(num).count('1') for num in list]
7+
return result
8+
9+
class Solution2:
10+
# time complexity: O(n * logn)
11+
# space complexity: O(1)
12+
def countBits(self, n: int) -> List[int]:
13+
14+
def count(num):
15+
cnt = 0
16+
while num:
17+
cnt += num % 2
18+
num //= 2
19+
return cnt
20+
21+
res = [count(i) for i in range(n+1)]
22+
return res
23+
24+
class Solution3:
25+
# time complexity: O(n)
26+
# space complexity: O(1)
27+
def countBits(self, n: int) -> List[int]:
28+
res = [0] * (n + 1)
29+
msb = 1
30+
for i in range(1, n + 1):
31+
if i == msb * 2:
32+
msb *= 2
33+
res[i] = res[i - msb] + 1
34+
return res

0 commit comments

Comments
 (0)