Skip to content

Commit 4a759e7

Browse files
committed
feat: add counting-bits sol
1 parent ab04033 commit 4a759e7

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

โ€Žcounting-bits/shinsj4653.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
11
"""
22
[๋ฌธ์ œํ’€์ด]
33
# Inputs
4-
4+
n: int
55
# Outputs
66
7+
ans: arr
8+
๊ธธ์ด: n + 1
9+
10+
ans๋‚ด ๊ฐ ์›์†Œ๋“ค : ans[i]: i์˜ ์ด์ง„๋ฒ•์—์„œ 1์˜ ๊ฐœ์ˆ˜
11+
712
# Constraints
13+
0 <= n <= 10^5
814
915
# Ideas
16+
2์ค‘ for๋ฌธ ์ด๋ฉด ์•ˆ๋จ
1017
1118
[ํšŒ๊ณ ]
12-
19+
dp๋ฅผ ํ™œ์šฉํ•œ ํ’€์ด๋„ ๊ฐ™์ด ์•Œ์•„๋‘์ž
1320
"""
1421

22+
# ๋‚ด ํ’€์ด
23+
class Solution:
24+
def countBits(self, n: int) -> List[int]:
25+
26+
ans = []
27+
28+
for i in range(n + 1):
29+
if i == 0 or i == 1:
30+
ans.append(i)
31+
continue
32+
33+
num = i
34+
cnt = 0
35+
while num > 0:
36+
num, n = num // 2, num % 2
37+
if n == 1:
38+
cnt += 1
39+
40+
ans.append(cnt)
41+
42+
return ans
43+
44+
# ํ•ด์„ค
45+
class Solution:
46+
def countBits(self, n: int) -> List[int]:
47+
dp = [0] * (n + 1)
48+
for num in range(1, n + 1):
49+
dp[num] = dp[num // 2] + (num % 2)
50+
return dp
51+
1552

0 commit comments

Comments
ย (0)