Drill

ProblemsPython › patterns

Is it a power of two

easypatternsBit manipulationMathPython

A page allocator only caps sizes at exact powers of two, and a build report flags a size that slipped through.

is_power_of_two(amount: int) → bool

Solve it in the editor →

Where you start

def is_power_of_two(amount: int) -> bool:
    

Worked examples

CallResult
is_power_of_two(1)True
is_power_of_two(2)True
is_power_of_two(4)True
is_power_of_two(6)False

Hint

A power of two has exactly one bit set. Clearing the lowest set bit with n & (n - 1) turns it to zero.

Reference solution in Python
def is_power_of_two(amount: int) -> bool:
    return amount > 0 and (amount & (amount - 1)) == 0

The same problem in another language

More patterns problems in Python