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 0d74bc3 commit ffcfb19Copy full SHA for ffcfb19
Python/LeetCode/338. Counting Bits.py
@@ -0,0 +1,24 @@
1
+# https://leetcode.com/problems/counting-bits/
2
+
3
+class Solution:
4
+ def countBits(self, num: int) -> [int]:
5
+ # return self.solution1(num)
6
+ return self.solution2(num)
7
8
+ # Time: O(n * sizeOf(int))
9
+ def solution1(self, num):
10
+ return list(map(lambda i: bin(i).count("1"), range(0, num + 1)))
11
12
+ # Time: O(n)
13
+ # even: countBits(i) == countBits(i // 2)
14
+ # odd: countBits(i) == countBits(i - 1) + 1 where (i - 1) is even
15
+ # 2: 00010
16
+ # 4: 00100
17
+ # 8: 01000
18
+ def solution2(self, num):
19
+ res = [0] * (num + 1)
20
+ for i in range(num + 1):
21
+ # or i >> 1 or i % 2
22
+ res[i] = res[i // 2] + (i & 1)
23
+ return res
24
0 commit comments