diff --git a/bit_manipulation/is_power_of_two.py b/bit_manipulation/is_power_of_two.py index 023e979fe51c..6c5633e2ffd5 100644 --- a/bit_manipulation/is_power_of_two.py +++ b/bit_manipulation/is_power_of_two.py @@ -12,6 +12,20 @@ n - 1 = 0..011..11 n & (n - 1) - no intersections = 0 + +New Implementation Author: Arun +Date: 16th October, 2025 + +Change Notes: +- Added type checks and value checks for robustness. +- Added an alternative method using math.log2 for educational purposes. + +New Implementation Details: +- The function raises a ValueError if the input number is negative. +- The function raises a TypeError if the input is not an integer. +- Uses math.log2 to get the exponent and checks if it's an integer. +- For all powers of 2, log2 will yield an integer value. +- For non-powers of 2, log2 will yield a non-integer value. """ @@ -51,6 +65,35 @@ def is_power_of_two(number: int) -> bool: return number & (number - 1) == 0 +def is_power_of_two_math(number: int) -> bool: + from math import log2 + + """ + Alternative method using math.log2 to check if number is a power of 2. + + >>> is_power_of_two_math(0) + True + >>> is_power_of_two_math(1) + True + >>> is_power_of_two_math(2) + True + >>> is_power_of_two_math(6) + False + >>> is_power_of_two_math(16) + True + """ + if not isinstance(number, int): + raise TypeError("number must be an integer") + if number < 0: + raise ValueError("number must not be negative") + + if number == 0: + return True + + value = log2(number) + return value == int(value) + + if __name__ == "__main__": import doctest