LeetCode.2859. 计算 K 置位下标对应元素的和

题目

题目链接

分析

这道题的题意很明确。就是求每一个下标的二进制中1的个数为k的下标所对应的元素值之和。

Java 中有 库函数 Integer.bitCount(num),这个函数的返回值就是 num 中 1 的个数。

代码

java 复制代码
class 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;
    }
}

扩展

万一人家不让用库函数怎么办呢?????

那我们就需要老老实实自己写函数了。

我们首先考虑,怎么求得一个数字num 包含 1 的个数。

我们都知道 1 & 任何数 都得任何数。

那么我们就可以让 1&这个数的每一位 如果等于1就代表最后一位是1,然后右移这个数字,判断num二进制数的倒数第二位是否是1,依次判断,直到这个数字被移动为 0 为止。

下面看一下这段的代码:

java 复制代码
 int find(int num) {
     int count = 0;
     while(num != 0) {
         if((num & 1) == 1) count++;
         num >>= 1;
     }
     return count;
 }

根据上面的函数find我们就知道了一个数字二进制中 1 的个数了,接下来就可以解决 leetCode上面的题目了:

java 复制代码
class Solution {
    public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
        int ans = 0;
        for(int i = 0;i < nums.size();i ++) {
            if(find(i) == k) {
                ans += nums.get(i);
            }
        }
        return ans;
    }

    int find(int num) {
        int count = 0;
        while(num != 0) {
            if((num & 1) == 1) count++;
            num >>= 1;
        }
        return count;
    }
}
相关推荐
政企项目老覃6 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水6 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR6 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵7 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽7 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2087 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民9 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21039 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil20810 小时前
leetcode 78子集
数据结构·算法·leetcode