Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions bit_manipulation/is_power_of_two.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""


Expand Down Expand Up @@ -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

Expand Down