Skip to content
StackDecode
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

  1. A power of two has exactly one set bit (1, 10, 100, 1000 in binary).
  2. Subtracting 1 turns that bit off and everything below it on.
  3. So for a positive n, n & (n − 1) is 0 only when n has a single set bit.
  4. Zero is not a power of two, so check n > 0 first.

Watch it run

Loading animation…