File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 338. Counting Bits
3+
4+ 0부터 n까지의 이진수에서 1의 개수 세기
5+
6+ ## 풀이A. 브루투포스
7+ - 전부 계산하기
8+
9+ ## 풀이B. DP
10+ ```
11+ 이진수 = (이진수 >> 1) + (이진수 & 1)
12+ ```
13+ - `i >> 1`: i의 비트를 오른쪽으로 1비트 이동(맨 오른쪽 한 칸 버림), `i // 2`와 같음
14+ - `i & 1`: `i`의 마지막 비트가 1인지 확인 (1이면 1 추가, 0이면 패스)
15+ - DP 테이블에서 이전 계산(i >> 1) 결과를 가져와서 현재 계산(i & 1) 결과를 더한다.
16+ '''
17+ class Solution :
18+ '''
19+ A. brute force
20+ SC: O(n log n)
21+ TC: O(n)
22+ '''
23+ def countBitsBF (self , n : int ) -> List [int ]:
24+ result = []
25+
26+ for i in range (n + 1 ): # TC: O(n)
27+ result .append (bin (i ).count ('1' )) # TC: O(log n)
28+
29+ return result
30+
31+ '''
32+ B. DP
33+ SC: O(n)
34+ TC: O(n)
35+ '''
36+ def countBits (self , n : int ) -> List [int ]:
37+ dp = [0 ] * (n + 1 )
38+
39+ for i in range (1 , n + 1 ): # TC: O(n)
40+ dp [i ] = dp [i >> 1 ] + (i & 1 ) # TC: O(1)
41+
42+ return dp
You can’t perform that action at this time.
0 commit comments