Bit manipulationAnimated
Check Power of Two
A positive n is a power of two iff n & (n−1) == 0.
Time
O(1)
Extra space
O(1)
Use it for
Alignment and size checks.
How it works
- A power of two has exactly one set bit (1, 10, 100, 1000 in binary).
- Subtracting 1 turns that bit off and everything below it on.
- So for a positive n, n & (n − 1) is 0 only when n has a single set bit.
- Zero is not a power of two, so check n > 0 first.
Watch it run
Loading animation…