Alternating Bits

easy

Check if binary has alternating bits (101010...)

Alternating Bits

Key Insight

n ^ (n >> 1) should be all 1s if bits alternate. Check (x & (x+1)) == 0.

Step 1Problem
5
5
=
0
0
0
0
0
1
0
1
76543210
101 - alternating?

Does 5 (101) have alternating bits?

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Alternating Bits

n ^ (n >> 1) should be all 1s if bits alternate. Check (x & (x+1)) == 0.

  1. Problem

    Does 5 (101) have alternating bits?

  2. XOR with Shifted

    5 ^ (5 >> 1) = 5 ^ 2 = 7

  3. Check All 1s

    If all 1s: x & (x+1) == 0

  4. Counter Example

    7 (111) → 7 ^ 3 = 4 (100). Not all 1s.

  5. Result

    5 HAS alternating bits!