File tree Expand file tree Collapse file tree 1 file changed +41
-7
lines changed Expand file tree Collapse file tree 1 file changed +41
-7
lines changed Original file line number Diff line number Diff line change 2
2
338. Counting Bits
3
3
https://leetcode.com/problems/counting-bits/description/
4
4
5
- Solution:
5
+ Solution 1 :
6
6
- Convert the number to binary string
7
7
- Sum the number of 1s in the binary string
8
8
- Append the sum to the output list
14
14
15
15
Space complexity: O(n)
16
16
- The output list has n elements
17
- """
18
-
19
-
20
- from typing import List
21
-
22
-
17
+
23
18
class Solution:
24
19
def countBits(self, n: int) -> List[int]:
25
20
output = []
@@ -29,3 +24,42 @@ def countBits(self, n: int) -> List[int]:
29
24
output.append(_sum)
30
25
31
26
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
You can’t perform that action at this time.
0 commit comments