File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ ์ ์ n์ด ์ฃผ์ด์ก์ ๋, 0๋ถํฐ n๊น์ง์ ๋ชจ๋ ์์ ๋ํด ๊ฐ ์๋ฅผ ์ด์ง์๋ก ํํํ์ ๋ 1์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
3+
4+ TC: O(N log N), ๋ชจ๋ ์ ์ํ + ์ด์ง์ ๋ณํ ๊ณผ์ (log i)
5+ SC: O(N)
6+ """
7+
8+ from typing import List
9+
10+ # ์ฒ์ ํ์ด
11+ class Solution :
12+ def countBits (self , n : int ) -> List [int ]:
13+ def countOne (num ):
14+ cnt = 0
15+ while True :
16+ rest = num % 2
17+ if rest == 1 :
18+ cnt += 1
19+ num //= 2
20+ if num <= 1 :
21+ if num == 1 :
22+ cnt += 1
23+ break
24+ return cnt
25+
26+ result = []
27+ for i in range (0 , n + 1 ):
28+ result .append (countOne (i ))
29+
30+ return result
31+
32+ """
33+ DP ํ์ด - ์๊ฐ ๋ณต์ก๋ ๊ฐ์
34+
35+ bits[i] = bits[i >> 1] + (i &)
36+ i >> 1 ์ i๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก 1๋นํธ ์ด๋ -> i๋ฅผ 2๋ก ๋๋ ๊ฐ
37+ i & 1 ์ i์ ๋ง์ง๋ง 1๋นํธ๊ฐ 1์ธ์ง ํ์ธ, ์ง์๋ฉด 0, ํ์๋ฉด 1
38+ i์ 1์ ๊ฐ์ = i๋ฅผ 2๋ก ๋๋ ์์ 1์ ๊ฐ์ + ๋ง์ง๋ง ๋นํธ๊ฐ 1์ธ์ง ์ฌ๋ถ
39+
40+ TC: O(N)
41+ SC: O(N)
42+ """
43+
44+ class Solution :
45+ def countBits (self , n : int ) -> List [int ]:
46+ dp = [0 ] * (n + 1 )
47+ for i in range (1 , n + 1 ):
48+ dp [i ] = dp [i >> 1 ] + (i & 1 )
49+ return dp
You canโt perform that action at this time.
0 commit comments