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:

  • 5 has binary representation 101 → alternating bits ✓
  • 7 has binary representation 111 → adjacent 1's ✗
  • 10 has binary representation 1010 → 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
Binary Number with Alternating BitsInputn = 5Binary Representation101OutputtrueCheck: 1 ≠ 0 ✓, 0 ≠ 1 ✓ → All bits alternateExamples:5 → 101 ✓ (alternating)7 → 111 ✗ (adjacent 1's)
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
Asked in
Google 15 Facebook 12 Microsoft 8
25.0K Views
Medium Frequency
~10 min Avg. Time
890 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