Binary Number with Alternating Bits - Problem
Given a positive integer, determine if it has alternating bits. A number has alternating bits if no two adjacent bits in its binary representation have the same value.
For example:
5has binary representation101→ alternating bits ✓7has binary representation111→ adjacent 1's ✗10has binary representation1010→ alternating bits ✓
Return true if the number has alternating bits, false otherwise.
Input & Output
Example 1 — Alternating Pattern
$
Input:
n = 5
›
Output:
true
💡 Note:
5 in binary is 101. Adjacent bits are different: 1→0→1, so return true
Example 2 — Non-Alternating Pattern
$
Input:
n = 7
›
Output:
false
💡 Note:
7 in binary is 111. Adjacent bits 1 and 1 are the same, so return false
Example 3 — Longer Alternating Pattern
$
Input:
n = 10
›
Output:
true
💡 Note:
10 in binary is 1010. All adjacent bits alternate: 1→0→1→0, so return true
Constraints
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Positive integer n
2
Process
Check if binary representation has alternating bits
3
Output
Return true if alternating, false otherwise
Key Takeaway
🎯 Key Insight: XOR operation reveals alternating patterns by producing all 1's when bits alternate
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code