Skip to content

Commit 13f1335

Browse files
committed
solve(w14): 338. Counting Bits
1 parent 80c82a8 commit 13f1335

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

counting-bits/seungriyou.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# https://leetcode.com/problems/counting-bits/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def countBits(self, n: int) -> List[int]:
7+
"""
8+
[Complexity]
9+
- TC: O(n)
10+
- SC: O(n)
11+
12+
[Approach]
13+
다음과 같은 규칙을 찾을 수 있다.
14+
15+
0 ~ 1 bin(0) = 0
16+
bin(1) = 1
17+
18+
2 ~ 3 bin(2) = 10 = 10 + bin(0)
19+
bin(3) = 11 = 10 + bin(1)
20+
=> offset = 10(2) = 2 (-> 1이 1개)
21+
22+
4 ~ 7 bin(4) = 100 = 100 + bin(0)
23+
bin(5) = 101 = 100 + bin(1)
24+
bin(6) = 110 = 100 + bin(2)
25+
bin(7) = 111 = 100 + bin(3)
26+
=> offset = 100(2) = 4 (-> 1이 1개)
27+
28+
8 ~ 15 bin(8) = 1000 = 1000 + bin(0)
29+
...
30+
bin(15) = 1111 = 1000 + bin(7)
31+
=> offset = 1000(2) = 8 (-> 1이 1개)
32+
"""
33+
34+
dp = [0] * (n + 1)
35+
offset = 1
36+
37+
for i in range(1, n + 1):
38+
# i가 2의 제곱이면, offset 2배
39+
if offset * 2 == i:
40+
offset *= 2
41+
42+
# 이전에 구한 값 사용
43+
dp[i] = dp[i - offset] + 1
44+
45+
return dp

0 commit comments

Comments
 (0)