Skip to content

Commit ffcfb19

Browse files
committed
LeetCode: 338 solved
1 parent 0d74bc3 commit ffcfb19

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Python/LeetCode/338. Counting Bits.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)