Skip to main content
Back to problems
#693
Easy Algorithms

Binary number with alternating bits

Bit Manipulation
69.8% acceptance
Feb 20, 2026
1724
125
Given a positive integer n, check whether it has alternating bits in binary.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn has_alternating_bits(n: i32) -> bool {
    let n = n as u32;
    let xor = n ^ (n >> 1);
    xor & (xor + 1) == 0
  }
}