当前位置:   article > 正文

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

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

题目描述:

https://leetcode.cn/problems/sum-of-values-at-indices-with-k-set-bits/description/

思路:

暴力枚举即可

题目描述在列表中的对应下标所对应的二进制的置位为k时,就加上这个下标对应的数。

思考对列表进行遍历,求出每个下标对应的置位个数,当满足题目要求时就加上该下标对应在列表中的值。

代码:

  1. class Solution {
  2. public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
  3. int res = 0;
  4. for(int i = 0;i<nums.size();i++) {
  5. if(bitCount(i) == k) {
  6. res += nums.get(i);
  7. }
  8. }
  9. return res;
  10. }
  11. //求下标对应的二进制中的置位数
  12. public static int bitCount(int x) {
  13. int cnt = 0;
  14. while(x!=0) {
  15. cnt += (x % 2);
  16. x/=2;
  17. }
  18. return cnt;
  19. }
  20. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号