Skip to main content
Back to problems
#2859
Easy Algorithms

Sum of values at indices with k set bits

Array Bit Manipulation
86.1% acceptance
Feb 25, 2026
317
50
You are given a 0-indexed integer array nums and an integer k. Return an integer that denotes the sum of elements in nums whose corresponding indices have exactly k set bits in their binary representation. The set bits in an integer are the 1's present when it is written in binary. For example, the binary representation of 21 is 10101, which has 3 set bits.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn sum_indices_with_k_set_bits(nums: Vec<i32>, k: i32) -> i32 {
    nums.iter().enumerate()
      .filter(|&(i, _)| (i as i32).count_ones() as i32 == k)
      .map(|(_, &v)| v)
      .sum()
  }
}