[LeetCode] 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.
Example 1:
Input: nums = [5,10,1,5,2], k = 1
Output: 13
Explanation: The binary representation of the indices are:
0 = 0002
1 = 0012
2 = 0102
3 = 0112
4 = 1002
Indices 1, 2, and 4 have k = 1 set bits in their binary representation.
Hence, the answer is nums[1] + nums[2] + nums[4] = 13.
Example 2:
Input: nums = [4,3,2,1], k = 2
Output: 1
Explanation: The binary representation of the indices are:
0 = 002
1 = 012
2 = 102
3 = 112
Only index 3 has k = 2 set bits in its binary representation.
Hence, the answer is nums[3] = 1.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 105
0 <= k <= 10
计算 K 置位下标对应元素的和。
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。
请你用整数形式返回 nums 中的特定元素之 和 ,这些特定元素满足:其对应下标的二进制表示中恰存在 k 个置位。
整数的二进制表示中的 1 就是这个整数的 置位 。
例如,21 的二进制表示为 10101 ,其中有 3 个置位。
思路
对于数组内的每一个数字,我们看一下数字的二进制表达里有几个 1,如果当前数字的二进制表达里 1 的个数等于这个数字在 input 数组内的下标,则把这个数字累加到结果里。
计算数字的二进制表达里有几个 1 等同于 191 题。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution { public int sumIndicesWithKSetBits(List<Integer> nums, int k) { int res = 0; int n = nums.size(); for (int i = 0; i < n; i++) { if (helper(i) == k) { res += nums.get(i); } } return res; } public int helper(int n) { int count = 0; while (n != 0) { n &= n - 1; count++; } return count; } }
相关题目
191. Number of 1 Bits 2859. Sum of Values at Indices With K Set Bits
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2023-01-25 [LeetCode] 1101. The Earliest Moment When Everyone Become Friends
2021-01-25 [LeetCode] 1657. Determine if Two Strings Are Close