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 Bits INPUT n = 5 Binary: 101 1 bit 2 0 bit 1 1 bit 0 Pattern: 1 - 0 - 1 (alternating) Input Details Decimal: 5 Binary: 101 ALGORITHM STEPS 1 XOR with shifted x = n ^ (n >> 1) 101 ^ 010 = 111 x = 7 (all 1s) 2 Check all 1s x & (x+1) == 0? 111 & 1000 = 0 7 & 8 = 0 3 Verify result Result equals 0 4 Return answer 0 == 0 is true Time: O(1) Space: O(1) FINAL RESULT true OK Verification: Binary of 5: 1 0 1 bit[2]=1, bit[1]=0 [OK] bit[1]=0, bit[0]=1 [OK] All adjacent bits differ! Output: true 5 has alternating bits Key Insight: When n has alternating bits, n XOR (n >> 1) produces all 1s. A number with all 1s (like 111) when ANDed with itself+1 (like 1000) equals 0. This bit manipulation trick gives O(1) solution! TutorialsPoint - Binary Number with Alternating Bits | Optimal Solution
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