forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_previous_power_of_two.py
30 lines (26 loc) · 967 Bytes
/
find_previous_power_of_two.py
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
29
30
deffind_previous_power_of_two(number: int) ->int:
"""
Find the largest power of two that is less than or equal to a given integer.
https://stackoverflow.com/questions/1322510
>>> [find_previous_power_of_two(i) for i in range(18)]
[0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
>>> find_previous_power_of_two(-5)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> find_previous_power_of_two(10.5)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
"""
ifnotisinstance(number, int) ornumber<0:
raiseValueError("Input must be a non-negative integer")
ifnumber==0:
return0
power=1
whilepower<=number:
power<<=1# Equivalent to multiplying by 2
returnpower>>1ifnumber>1else1
if__name__=="__main__":
importdoctest
doctest.testmod()