Skip to content

2859. Sum of Values at Indices With K Set Bits 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int sumIndicesWithKSetBits(vector<int>& nums, int k) {
    int ans = 0;
    for (unsigned i = 0; i < nums.size(); ++i)
      if (popcount(i) == k)
        ans += nums[i];
    return ans;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
    int ans = 0;
    for (int i = 0; i < nums.size(); ++i)
      if (Integer.bitCount(i) == k)
        ans += nums.get(i);
    return ans;
  }
}
1
2
3
4
class Solution:
  def sumIndicesWithKSetBits(self, nums: list[int], k: int) -> int:
    return sum(num for i, num in enumerate(nums)
               if i.bit_count() == k)