Binary Number with Alternating Bits - Problem

Given a positive integer, determine if its binary representation contains alternating bits. In other words, check if every two adjacent bits in the binary form have different values (no two consecutive 0s or 1s).

For example:

  • 5 in binary is 101 → alternating ✓
  • 7 in binary is 111 → not alternating ✗
  • 10 in binary is 1010 → alternating ✓

Goal: Return true if the number has alternating bits, false otherwise.

Input & Output

example_1.py — Simple Alternating
$ Input: n = 5
Output: true
💡 Note: 5 in binary is '101'. Adjacent bits are: 1≠0, 0≠1. All adjacent bits are different, so return true.
example_2.py — Non-Alternating
$ Input: n = 7
Output: false
💡 Note: 7 in binary is '111'. Adjacent bits are: 1=1, 1=1. Adjacent bits are the same, so return false.
example_3.py — Longer Alternating
$ Input: n = 10
Output: true
💡 Note: 10 in binary is '1010'. Adjacent bits are: 1≠0, 0≠1, 1≠0. All adjacent bits alternate, so return true.

Constraints

  • 1 ≤ n ≤ 231 - 1
  • n is a positive integer
  • Return type is boolean

Visualization

Tap to expand
🎄 Binary Christmas Lights Pattern Detective1010Perfect Alternating Pattern: 1010🔍 Detective Method (XOR Trick):1010 XOR 0101 = 1111 (all 1s = alternating confirmed!)1111 & 10000 = 0 ✓ (power of 2 minus 1 check)VALIDPattern Detected: ALTERNATING
Understanding the Visualization
1
Examine the Pattern
Look at the binary representation to see the bit sequence
2
Apply XOR Magic
XOR the number with its right-shifted version to highlight differences
3
Check for All 1s
If alternating, the XOR result will be all 1s (111, 1111, etc.)
4
Verify Power of 2 - 1
Use (xor & (xor + 1)) == 0 to confirm the pattern
Key Takeaway
🎯 Key Insight: XOR operation between a number and its right-shifted version creates all 1s pattern (2^k - 1) if and only if the original bits were alternating. This mathematical property allows O(1) detection!
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
42.3K Views
Medium Frequency
~8 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen