Math Fundamentals18 sections · 814 units
Open in Course

Checking Power of Two

One-line trick

A number is a power of 2 if it has exactly one bit set. For example, 8=10008 = 1000, 16=1000016 = 10000, 32=10000032 = 100000.

Here's the trick: a number nn is a power of 2 if and only if n>0n > 0 and n&(n1)=0n \& (n-1) = 0.

Why? If nn has exactly one bit set, then n1n-1 flips that bit and all bits to the right. ANDing them gives 0. But if nn has multiple bits set, n&(n1)n \& (n-1) only clears the rightmost one, leaving others, so the result is non-zero. This check runs in O(1)O(1) time.