We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c528fd2 commit 94adc07Copy full SHA for 94adc07
counting-bits/samthekorean.py
@@ -1,15 +1,10 @@
1
-# TC : O(nlog(n))
2
-# SC : O(n)
+# TC: O(n)
+# SC: O(n)
3
+# For each number from 1 to n, update the count of set bits for i based on the count for i divided by two
4
+# and the least significant bit (LSB) of i.
5
class Solution:
6
def countBits(self, n: int) -> List[int]:
- count = 0
- ans = []
7
-
8
- for i in range(n + 1):
9
- while i > 0:
10
- count += i % 2
11
- i = i // 2
12
- ans.append(count)
13
14
+ ans = [0] * (n + 1)
+ for i in range(1, n + 1):
+ ans[i] = ans[i >> 1] + (i & 1)
15
return ans
0 commit comments