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
21is10101, which has3set bits.
Example 1
Input
nums = [5,10,1,5,2], k = 1Output
13Indices 1, 2, and 4 have exactly k = 1 set bit in their binary representation, so the sum is nums[1] + nums[2] + nums[4] = 13.
Example 2
Input
nums = [4,3,2,1], k = 2Output
1Only index 3 has exactly k = 2 set bits in its binary representation, so the sum is nums[3] = 1.
Constraints
- 1 <= nums.length <= 1000
- 1 <= nums[i] <= 10^5
- 0 <= k <= 10