Skip to content

Commit 299592b

Browse files
authored
dynamic programming for counting-bits
1 parent d4dbdae commit 299592b

File tree

1 file changed

+41
-7
lines changed

1 file changed

+41
-7
lines changed

counting-bits/bhyun-kim.py

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
338. Counting Bits
33
https://leetcode.com/problems/counting-bits/description/
44
5-
Solution:
5+
Solution 1:
66
- Convert the number to binary string
77
- Sum the number of 1s in the binary string
88
- Append the sum to the output list
@@ -14,12 +14,7 @@
1414
1515
Space complexity: O(n)
1616
- The output list has n elements
17-
"""
18-
19-
20-
from typing import List
21-
22-
17+
2318
class Solution:
2419
def countBits(self, n: int) -> List[int]:
2520
output = []
@@ -29,3 +24,42 @@ def countBits(self, n: int) -> List[int]:
2924
output.append(_sum)
3025
3126
return output
27+
"""
28+
29+
"""
30+
Solution 2
31+
We can solve this problem with dynamic programming.
32+
1. Initialize output with n elements
33+
2. The first element is 0 because iteration starts from zero.
34+
3. Iterate from 1 to n+1
35+
4. The last digit of each number is 0 for even number 1 for odd number
36+
So add (i & 1) to the output
37+
5. The digits except the last one can be found when the number is divided by two.
38+
Instead for division by two, we can use one step of bit shift to the right.
39+
40+
0 = 00000
41+
1 = 00001
42+
2 = 00010
43+
3 = 00011
44+
4 = 00100
45+
5 = 00101
46+
6 = 00110
47+
7 = 00111
48+
49+
Time complexity: O(n)
50+
- The for loop runs n times
51+
52+
Space complexity: O(n)
53+
- The output list has n elements
54+
"""
55+
56+
from typing import List
57+
58+
class Solution:
59+
def countBits(self, n: int) -> List[int]:
60+
output = [0] * (n+1)
61+
62+
for i in range(1, n+1):
63+
output[i] = output[i >> 1] + (i & 1)
64+
65+
return output

0 commit comments

Comments
 (0)