2859. Sum of Values at Indices With K Set Bits ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10class 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 9class 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 4class Solution: def sumIndicesWithKSetBits(self, nums: list[int], k: int) -> int: return sum(num for i, num in enumerate(nums) if i.bit_count() == k)