Skip to content

Commit 4e6c1c0

Browse files
alexpantyukhinpre-commit-ci[bot]cclauss
authored
Is power of two (TheAlgorithms#7936)
* add is power of two * fix comment * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Deal with negative numbers * Spelling: negative 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 d23e709 commit 4e6c1c0

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

bit_manipulation/is_power_of_two.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Author : Alexander Pantyukhin
3+
Date : November 1, 2022
4+
5+
Task:
6+
Given a positive int number. Return True if this number is power of 2
7+
or False otherwise.
8+
9+
Implementation notes: Use bit manipulation.
10+
For example if the number is the power of two it's bits representation:
11+
n = 0..100..00
12+
n - 1 = 0..011..11
13+
14+
n & (n - 1) - no intersections = 0
15+
"""
16+
17+
18+
def is_power_of_two(number: int) -> bool:
19+
"""
20+
Return True if this number is power of 2 or False otherwise.
21+
22+
>>> is_power_of_two(0)
23+
True
24+
>>> is_power_of_two(1)
25+
True
26+
>>> is_power_of_two(2)
27+
True
28+
>>> is_power_of_two(4)
29+
True
30+
>>> is_power_of_two(6)
31+
False
32+
>>> is_power_of_two(8)
33+
True
34+
>>> is_power_of_two(17)
35+
False
36+
>>> is_power_of_two(-1)
37+
Traceback (most recent call last):
38+
...
39+
ValueError: number must not be negative
40+
>>> is_power_of_two(1.2)
41+
Traceback (most recent call last):
42+
...
43+
TypeError: unsupported operand type(s) for &: 'float' and 'float'
44+
45+
# Test all powers of 2 from 0 to 10,000
46+
>>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
47+
True
48+
"""
49+
if number < 0:
50+
raise ValueError("number must not be negative")
51+
return number & (number - 1) == 0
52+
53+
54+
if __name__ == "__main__":
55+
import doctest
56+
57+
doctest.testmod()

0 commit comments

Comments
 (0)