Power of Two

easy

Check if a number is a power of two

Power of Two

Key Insight

Power of 2 has exactly one 1-bit. n & (n-1) == 0 for powers of 2.

Step 1Powers of 2
8
8
=
0
0
0
0
1
0
0
0
76543210
8 = 1000

1, 2, 4, 8... all have exactly one 1-bit.

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Power of Two

Power of 2 has exactly one 1-bit. n & (n-1) == 0 for powers of 2.

  1. Powers of 2

    1, 2, 4, 8... all have exactly one 1-bit.

  2. The Trick

    n & (n-1) clears the lowest 1-bit.

  3. Power of 2: Yes

    If result is 0, it's a power of 2!

  4. Not Power of 2

    6 & 5 = 4 ≠ 0. Not a power of 2.

  5. Result

    n > 0 && (n & (n-1)) == 0