-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsolution.py
More file actions
19 lines (15 loc) · 545 Bytes
/
Copy pathsolution.py
File metadata and controls
19 lines (15 loc) · 545 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def count_bits(self, n: int) -> list[int]:
"""
Optimized version with better variable naming and comments.
Time: O(n)
Space: O(1) excluding output array
"""
if n == 0:
return [0]
bits_count = [0] * (n + 1)
for num in range(1, n + 1):
# For any number, the count of 1s equals:
# count of 1s in (num >> 1) + whether the last bit is 1
bits_count[num] = bits_count[num >> 1] + (num & 1)
return bits_count