File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution1 :
2+ # time complexity: O(n)
3+ # space complexity: O(1)
4+ def countBits (self , n : int ) -> List [int ]:
5+ list = [i for i in range (n + 1 )]
6+ result = [bin (num ).count ('1' ) for num in list ]
7+ return result
8+
9+ class Solution2 :
10+ # time complexity: O(n * logn)
11+ # space complexity: O(1)
12+ def countBits (self , n : int ) -> List [int ]:
13+
14+ def count (num ):
15+ cnt = 0
16+ while num :
17+ cnt += num % 2
18+ num //= 2
19+ return cnt
20+
21+ res = [count (i ) for i in range (n + 1 )]
22+ return res
23+
24+ class Solution3 :
25+ # time complexity: O(n)
26+ # space complexity: O(1)
27+ def countBits (self , n : int ) -> List [int ]:
28+ res = [0 ] * (n + 1 )
29+ msb = 1
30+ for i in range (1 , n + 1 ):
31+ if i == msb * 2 :
32+ msb *= 2
33+ res [i ] = res [i - msb ] + 1
34+ return res
You can’t perform that action at this time.
0 commit comments