|
12 | 12 | n - 1 = 0..011..11 |
13 | 13 |
|
14 | 14 | n & (n - 1) - no intersections = 0 |
| 15 | +
|
| 16 | +New Implementation Author: Arun |
| 17 | +Date: 16th October, 2025 |
| 18 | +
|
| 19 | +Change Notes: |
| 20 | +- Added type checks and value checks for robustness. |
| 21 | +- Added an alternative method using math.log2 for educational purposes. |
| 22 | +
|
| 23 | +New Implementation Details: |
| 24 | +- The function raises a ValueError if the input number is negative. |
| 25 | +- The function raises a TypeError if the input is not an integer. |
| 26 | +- Uses math.log2 to get the exponent and checks if it's an integer. |
| 27 | +- For all powers of 2, log2 will yield an integer value. |
| 28 | +- For non-powers of 2, log2 will yield a non-integer value. |
15 | 29 | """ |
16 | 30 |
|
17 | 31 |
|
@@ -50,8 +64,35 @@ def is_power_of_two(number: int) -> bool: |
50 | 64 | raise ValueError("number must not be negative") |
51 | 65 | return number & (number - 1) == 0 |
52 | 66 |
|
| 67 | +def is_power_of_two_math(number: int) -> bool: |
| 68 | + from math import log2 |
| 69 | + """ |
| 70 | + Alternative method using math.log2 to check if number is a power of 2. |
| 71 | + |
| 72 | + >>> is_power_of_two_math(0) |
| 73 | + True |
| 74 | + >>> is_power_of_two_math(1) |
| 75 | + True |
| 76 | + >>> is_power_of_two_math(2) |
| 77 | + True |
| 78 | + >>> is_power_of_two_math(6) |
| 79 | + False |
| 80 | + >>> is_power_of_two_math(16) |
| 81 | + True |
| 82 | + """ |
| 83 | + if not isinstance(number, int): |
| 84 | + raise TypeError("number must be an integer") |
| 85 | + if number < 0: |
| 86 | + raise ValueError("number must not be negative") |
| 87 | + |
| 88 | + if number == 0: |
| 89 | + return True |
| 90 | + |
| 91 | + value = log2(number) |
| 92 | + return value == int(value) |
53 | 93 |
|
54 | 94 | if __name__ == "__main__": |
55 | 95 | import doctest |
56 | 96 |
|
57 | 97 | doctest.testmod() |
| 98 | + |
0 commit comments