Power of Two Check
A power of two has exactly one set bit, so n & (n−1) — which clears the lowest set bit — yields zero only for powers of two (and n must be positive).
- Category
- Bit Manipulation
- Time complexity
- O(1)
- Space complexity
- O(1)
Pseudocode
powers of two have one 1-bit n & (n−1) clears the lowest 1 result 0 ⇔ power of two
Reference implementation
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0