We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e2a78d4 commit 5199e18Copy full SHA for 5199e18
1 file changed
maths/power_of_two.py
@@ -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
15
+ >>> is_power_of_two(3)
16
+ False
17
+ >>> is_power_of_two(0)
18
19
+ >>> is_power_of_two(-4)
20
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