Skip to content

Commit 6c76687

Browse files
committed
Create counting-bits.py
1 parent 0581a4f commit 6c76687

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/counting-bits.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Given a non negative integer number num. For every numbers i
5+
# in the range 0 <= i <= num calculate the number
6+
# of 1's in their binary representation and return them as an array.
7+
#
8+
# Example:
9+
# For num = 5 you should return [0,1,1,2,1,2].
10+
#
11+
# Follow up:
12+
#
13+
# It is very easy to come up with a solution with run
14+
# time O(n*sizeof(integer)). But can you do it in
15+
# linear time O(n) /possibly in a single pass?
16+
# Space complexity should be O(n).
17+
# Can you do it like a boss? Do it without using
18+
# any builtin function like __builtin_popcount in c++ or
19+
# in any other language.
20+
# Hint:
21+
#
22+
# 1. You should make use of what you have produced already.
23+
# 2. Divide the numbers in ranges like [2-3], [4-7], [8-15]
24+
# and so on. And try to generate new range from previous.
25+
# 3. Or does the odd/even status of the number help you in
26+
# calculating the number of 1s?
27+
28+
class Solution(object):
29+
def countBits(self, num):
30+
"""
31+
:type num: int
32+
:rtype: List[int]
33+
"""
34+
res = [0]
35+
for i in xrange(1, num + 1):
36+
res.append(res[i >> 1] + (i & 1))
37+
return res

0 commit comments

Comments
 (0)