TheAlgorithms-Python

Форк
0
57 строк · 1.3 Кб
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()
58

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.