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 22338. Counting Bits
33https://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
1414
1515Space complexity: O(n)
1616 - The output list has n elements
17- """
18-
19-
20- from typing import List
21-
22-
17+
2318class 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
You can’t perform that action at this time.
0 commit comments