Skip to content

Commit 8217f9b

Browse files
its-tapaspre-commit-ci[bot]cclauss
authored
Create find_previous_power_of_two.py (TheAlgorithms#11004)
* Create find_previous_power_of_two.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update find_previous_power_of_two.py This change avoids the unnecessary left shift operation * Update find_previous_power_of_two.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent adb13a1 commit 8217f9b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def find_previous_power_of_two(number: int) -> int:
2+
"""
3+
Find the largest power of two that is less than or equal to a given integer.
4+
https://stackoverflow.com/questions/1322510
5+
6+
>>> [find_previous_power_of_two(i) for i in range(18)]
7+
[0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
8+
>>> find_previous_power_of_two(-5)
9+
Traceback (most recent call last):
10+
...
11+
ValueError: Input must be a non-negative integer
12+
>>> find_previous_power_of_two(10.5)
13+
Traceback (most recent call last):
14+
...
15+
ValueError: Input must be a non-negative integer
16+
"""
17+
if not isinstance(number, int) or number < 0:
18+
raise ValueError("Input must be a non-negative integer")
19+
if number == 0:
20+
return 0
21+
power = 1
22+
while power <= number:
23+
power <<= 1 # Equivalent to multiplying by 2
24+
return power >> 1 if number > 1 else 1
25+
26+
27+
if __name__ == "__main__":
28+
import doctest
29+
30+
doctest.testmod()

0 commit comments

Comments
 (0)