[LeetCode] Sum of Values at Indices With K Set Bits

2859. Sum of Values at Indices With K Set Bits

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.
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int sumIndicesWithKSetBits(vector<int>& nums, int k) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
if(__builtin_popcount(i) == k) res += nums[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/17/PS/LeetCode/sum-of-values-at-indices-with-k-set-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.