forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshinsj4653.py
More file actions
52 lines (38 loc) ยท 891 Bytes
/
shinsj4653.py
File metadata and controls
52 lines (38 loc) ยท 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
[๋ฌธ์ ํ์ด]
# Inputs
n: int
# Outputs
ans: arr
๊ธธ์ด: n + 1
ans๋ด ๊ฐ ์์๋ค : ans[i]: i์ ์ด์ง๋ฒ์์ 1์ ๊ฐ์
# Constraints
0 <= n <= 10^5
# Ideas
2์ค for๋ฌธ ์ด๋ฉด ์๋จ
[ํ๊ณ ]
dp๋ฅผ ํ์ฉํ ํ์ด๋ ๊ฐ์ด ์์๋์
"""
# ๋ด ํ์ด
class Solution:
def countBits(self, n: int) -> List[int]:
ans = []
for i in range(n + 1):
if i == 0 or i == 1:
ans.append(i)
continue
num = i
cnt = 0
while num > 0:
num, n = num // 2, num % 2
if n == 1:
cnt += 1
ans.append(cnt)
return ans
# ํด์ค
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for num in range(1, n + 1):
dp[num] = dp[num // 2] + (num % 2)
return dp