Skip to content

Commit b4e0667

Browse files
committed
338. Counting Bits
1 parent 5f668ea commit b4e0667

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

โ€Žcounting-bits/socow.pyโ€Ž

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
338. Counting Bits
3+
https://leetcode.com/problems/counting-bits/
4+
5+
Solution:
6+
DP๋ฅผ ํ™œ์šฉํ•œ ํ’€์ด
7+
- i์˜ 1๋น„ํŠธ ๊ฐœ์ˆ˜ = (i // 2)์˜ 1๋น„ํŠธ ๊ฐœ์ˆ˜ + (i % 2)
8+
- i // 2๋Š” i๋ฅผ ์˜ค๋ฅธ์ชฝ์œผ๋กœ 1๋น„ํŠธ shiftํ•œ ๊ฒƒ (์ด๋ฏธ ๊ณ„์‚ฐ๋œ ๊ฐ’)
9+
- i % 2๋Š” LSB(์ตœํ•˜์œ„ ๋น„ํŠธ)๊ฐ€ 1์ธ์ง€ ์—ฌ๋ถ€
10+
11+
์˜ˆ์‹œ: 5 = 101(2)
12+
- 5 // 2 = 2 = 10(2) โ†’ 1๋น„ํŠธ 1๊ฐœ
13+
- 5 % 2 = 1 โ†’ LSB๊ฐ€ 1
14+
- ๋”ฐ๋ผ์„œ 5์˜ 1๋น„ํŠธ ๊ฐœ์ˆ˜ = 1 + 1 = 2
15+
16+
Time: O(n)
17+
Space: O(1) - ๊ฒฐ๊ณผ ๋ฐฐ์—ด ์ œ์™ธ
18+
"""
19+
20+
from typing import List
21+
22+
23+
class Solution:
24+
def countBits(self, n: int) -> List[int]:
25+
dp = [0] * (n + 1)
26+
27+
for i in range(1, n + 1):
28+
dp[i] = dp[i >> 1] + (i & 1)
29+
30+
return dp

0 commit comments

Comments
ย (0)