← Bit Manipulation

Drill #84 — Power of two

Easy Bit Check Bit Manipulation

In plain English: Determine if a number is an exact power of 2 (like 1, 2, 4, 8, 16, ...).

A power of 2 has exactly one set bit. n & (n-1) clears it, leaving 0 โ€” if not a power of 2, other bits remain.

Prompt

Check if a given positive integer n is a power of two.

Try to write it from scratch before scrolling down.

Solution

def is_power_of_two(n):
    # exactly one set bit means power of 2; n-1 flips it and all lower bits
    return n > 0 and (n & (n - 1)) == 0

# Test: is_power_of_two(16) == True
# Test: is_power_of_two(18) == False
# Test: is_power_of_two(1) == True
O(1) time ยท O(1) space

Related Micro Drills

← Drill #83 Drill #85 →