forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower_of_two.py
More file actions
35 lines (26 loc) · 764 Bytes
/
power_of_two.py
File metadata and controls
35 lines (26 loc) · 764 Bytes
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
31
32
33
34
35
"""
Power of Two
Determine whether a given integer is a power of two using bit manipulation.
A power of two has exactly one set bit, so ``n & (n - 1)`` clears that bit
and yields zero.
Reference: https://en.wikipedia.org/wiki/Power_of_two
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annotations
def is_power_of_two(number: int) -> bool:
"""Check whether an integer is a power of two.
Args:
number: The integer to test.
Returns:
True if *number* is a positive power of two, False otherwise.
Examples:
>>> is_power_of_two(64)
True
>>> is_power_of_two(91)
False
>>> is_power_of_two(0)
False
"""
return number > 0 and not number & (number - 1)