Input: nums =[5,10,1,5,2], k =1Output: 13Explanation: The binary representation of the indices are:0=00021=00122=01023=01124=1002Indices 1,2, and 4 have k =1 set bits in their binary representation.Hence, the answer is nums[1]+ nums[2]+ nums[4]=13.
Input: nums =[4,3,2,1], k =2Output: 1Explanation: The binary representation of the indices are:0=0021=0122=1023=112Only index 3 has k =2 set bits in its binary representation.Hence, the answer is nums[3]=1.
classSolution {
public:int sumIndicesWithKSetBits(vector<int>& nums, int k) {
int ans =0;
for (int i =0; i < nums.size(); ++i) {
if (__builtin_popcount(i) == k) ans += nums[i];
}
return ans;
}
};
classSolution {
publicintsumIndicesWithKSetBits(int[] nums, int k) {
int ans = 0;
for (int i = 0; i < nums.length; ++i) {
if (Integer.bitCount(i) == k) ans += nums[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funsumIndicesWithKSetBits(nums: IntArray, k: Int): Int {
var ans = 0for (i in nums.indices) {
if (i.countOneBits() == k) ans += nums[i]
}
return ans
}
}
1
2
3
classSolution:
defsumIndicesWithKSetBits(self, nums: list[int], k: int) -> int:
return sum(x for i, x in enumerate(nums) if bin(i).count('1') == k)