Skip to content

Commit 5199e18

Browse files
authored
Create power_of_two.py
1 parent e2a78d4 commit 5199e18

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

maths/power_of_two.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Check if an integer is a power of two.
3+
4+
Time Complexity: O(1)
5+
Space Complexity: O(1)
6+
"""
7+
8+
def is_power_of_two(n: int) -> bool:
9+
"""Return True if n is a power of two (n > 0).
10+
11+
>>> is_power_of_two(1)
12+
True
13+
>>> is_power_of_two(2)
14+
True
15+
>>> is_power_of_two(3)
16+
False
17+
>>> is_power_of_two(0)
18+
False
19+
>>> is_power_of_two(-4)
20+
False
21+
"""
22+
if not isinstance(n, int):
23+
raise TypeError("n must be an integer")
24+
return n > 0 and (n & (n - 1)) == 0
25+
26+
27+
if __name__ == "__main__":
28+
import doctest
29+
doctest.testmod()

0 commit comments

Comments
 (0)