#2595
Easy Algorithms Number of even and odd bits
Bit Manipulation
73.4% acceptance
Feb 25, 2026
371
117
You are given a positive integer n.
Let even denote the number of even indices in the binary representation of n with value 1.
Let odd denote the number of odd indices in the binary representation of n with value 1.
Note that bits are indexed from right to left in the binary representation of a number.
Return the array [even, odd].
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn even_odd_bit(n: i32) -> Vec<i32> {
// Count bits set at even indices (0,2,4,...) and odd indices (1,3,5,...).
let mut even = 0;
let mut odd = 0;
let mut x = n;
let mut idx = 0;
while x > 0 {
if x & 1 == 1 {
if idx % 2 == 0 { even += 1; } else { odd += 1; }
}
x >>= 1;
idx += 1;
}
vec![even, odd]
}
}