# 18.02.2026 [693. Binary Number with Alternating Bits]
Alternating bits #easy #bits
18.02.2026
693. Binary Number with Alternating Bits easy blog post substack youtube
Join me on Telegram
Problem TLDR
Alternating bits #easy #bits
Intuition
Check 31 bits with brute force.
The “clever solutions”:
shift right by 2 positions, should match; shift right by 1 positions, should be opposite
shift right by 1 position, do or: should be all ones
Approach
regex: (00|11)
Complexity
Time complexity: $$O(1)$$
Space complexity: $$O(1)$$
Code
// 0ms
fun hasAlternatingBits(n: Int) =
n or n/4 == n && n and n/2 == 0
/*
Regex("(11|00)") !in n.toString(2)
(n xor n/2).toString(2).all { it == '1' }
*/
// 0ms
pub fn has_alternating_bits(mut n: i32) -> bool {
n ^= n/2; n & n+1 == 0
}


