TheAlgorithms-Python
57 строк · 1.3 Кб
1"""
2Author : Alexander Pantyukhin
3Date : November 1, 2022
4
5Task:
6Given a positive int number. Return True if this number is power of 2
7or False otherwise.
8
9Implementation notes: Use bit manipulation.
10For example if the number is the power of two it's bits representation:
11n = 0..100..00
12n - 1 = 0..011..11
13
14n & (n - 1) - no intersections = 0
15"""
16
17
18def is_power_of_two(number: int) -> bool:19"""20Return True if this number is power of 2 or False otherwise.
21
22>>> is_power_of_two(0)
23True
24>>> is_power_of_two(1)
25True
26>>> is_power_of_two(2)
27True
28>>> is_power_of_two(4)
29True
30>>> is_power_of_two(6)
31False
32>>> is_power_of_two(8)
33True
34>>> is_power_of_two(17)
35False
36>>> is_power_of_two(-1)
37Traceback (most recent call last):
38...
39ValueError: number must not be negative
40>>> is_power_of_two(1.2)
41Traceback (most recent call last):
42...
43TypeError: 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))
47True
48"""
49if number < 0:50raise ValueError("number must not be negative")51return number & (number - 1) == 052
53
54if __name__ == "__main__":55import doctest56
57doctest.testmod()58