File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments