We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5f668ea commit b4e0667Copy full SHA for b4e0667
1 file changed
โcounting-bits/socow.pyโ
@@ -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