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:
5in binary is101→ alternating ✓7in binary is111→ not alternating ✗10in binary is1010→ 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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code