赞
踩
题目描述:
https://leetcode.cn/problems/sum-of-values-at-indices-with-k-set-bits/description/
思路:
暴力枚举即可
题目描述在列表中的对应下标所对应的二进制的置位为k时,就加上这个下标对应的数。
思考对列表进行遍历,求出每个下标对应的置位个数,当满足题目要求时就加上该下标对应在列表中的值。
代码:
- class Solution {
- public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
- int res = 0;
- for(int i = 0;i<nums.size();i++) {
- if(bitCount(i) == k) {
- res += nums.get(i);
- }
- }
- return res;
- }
- //求下标对应的二进制中的置位数
- public static int bitCount(int x) {
- int cnt = 0;
- while(x!=0) {
- cnt += (x % 2);
- x/=2;
- }
- return cnt;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。