- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcounting_bits.py
More file actions
Latest commit
28 lines (23 loc) · 588 Bytes
/
Copy pathcounting_bits.py
File metadata and controls
28 lines (23 loc) · 588 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
Task:
Given a non negative integer number num. For every numbers i in the range
0 ≤ i ≤ num calculate the number of 1's in their binary representation and
return them as an array.
>>> count_bits(2)
[0, 1, 1]
>>> count_bits(5)
[0, 1, 1, 2, 1, 2]
"""
defcount_bits(num):
ifnum==0:
return [0]
elifnum==1:
return [0, 1]
result= [0] * (num+1)
result[1] =1
foriinrange(2, num+1):
result[i] =result[i//2] +result[i%2]
returnresult
if__name__=='__main__':
importdoctest
doctest.testmod()