Binary Number with Alternating Bits
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Examples
Example 1
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints
1 <= n <= 2^31 - 1
Solution
Method 1 – Bit Manipulation (XOR and Check)
Intuition
If a number has alternating bits, then XORing it with itself right-shifted by 1 will result in a sequence of 1s (i.e., all bits set to 1). For example, 101 (5) XOR 010 (2) = 111 (7). If the result is a sequence of 1s, then adding 1 to it will make it a power of two, so result & (result + 1) == 0.
Approach
- Compute
x = n ^ (n >> 1). - Check if
x & (x + 1) == 0. - Return true if so, else false.
Code
C++
class Solution {
public:
bool hasAlternatingBits(int n) {
int x = n ^ (n >> 1);
return (x & (x + 1)) == 0;
}
};
Go
func hasAlternatingBits(n int) bool {
x := n ^ (n >> 1)
return x&(x+1) == 0
}
Java
class Solution {
public boolean hasAlternatingBits(int n) {
int x = n ^ (n >> 1);
return (x & (x + 1)) == 0;
}
}
Kotlin
class Solution {
fun hasAlternatingBits(n: Int): Boolean {
val x = n xor (n shr 1)
return (x and (x + 1)) == 0
}
}
Python
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
x = n ^ (n >> 1)
return (x & (x + 1)) == 0
Rust
impl Solution {
pub fn has_alternating_bits(n: i32) -> bool {
let x = n ^ (n >> 1);
(x & (x + 1)) == 0
}
}
Complexity
- ⏰ Time complexity:
O(1)— Only a few bitwise operations. - 🧺 Space complexity:
O(1)— No extra space used.