Skip to content

Commit 291558d

Browse files
Add math-based power of two check and input validation
Introduced is_power_of_two_math using math.log2 for educational purposes. Added type and value checks to both implementations for robustness, raising appropriate exceptions for invalid input.
1 parent 3cea941 commit 291558d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

bit_manipulation/is_power_of_two.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,20 @@
1212
n - 1 = 0..011..11
1313
1414
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.
1529
"""
1630

1731

@@ -50,8 +64,35 @@ def is_power_of_two(number: int) -> bool:
5064
raise ValueError("number must not be negative")
5165
return number & (number - 1) == 0
5266

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)
5393

5494
if __name__ == "__main__":
5595
import doctest
5696

5797
doctest.testmod()
98+

0 commit comments

Comments
 (0)