首页 > 其他分享 >【LeeCode】338. 比特位计数

【LeeCode】338. 比特位计数

时间:2022-12-18 18:00:28浏览次数:61  
标签:countBits return 338 比特 int res LeeCode import new

【题目描述】

给你一个整数 ​​n​​ ,对于 ​​0 <= i <= n​​ 中的每个 ​​i​​ ,计算其二进制表示中 ​​1​​​ 的个数 ,返回一个长度为 ​​n + 1​​ 的数组 ​​ans​​ 作为答案。

​https://leetcode.cn/problems/counting-bits/?favorite=2cktkvj​


【示例】

【LeeCode】338. 比特位计数_数组

【代码】admin

Integer.toBinaryString(i);   // 十进制转二进制
Integer.bitCount(i) // 统计二进制中1的数量
import java.math.BigInteger;
import java.util.*;
import java.util.regex.Pattern;
// 2022-12-17

class Solution {

public int[] countBits(int n) {
if ( n < 0) return null;
int[] res = new int[n+1];

for (int i = 0; i <= n; i++){
int count = Integer.bitCount(i);
res[i] = count;
}
return res;
}
}

public class Main{
public static void main(String[] args) {
int n = 5;
new Solution().countBits(n);

}
}


【代码】Offical

public int[] countBits(int n) {
if ( n < 0) return null;
int[] res = new int[n+1];

for (int i = 0; i <= n; i++){
res[i] = countOnes(i);
}
return res;
}

private int countOnes(int x) {
int one = 0;
while (x > 0) {
x &= (x - 1); // 相同为1
one++;
}
return one;
}


标签:countBits,return,338,比特,int,res,LeeCode,import,new
From: https://blog.51cto.com/u_13682316/5950946

相关文章

  • 【LeeCode】697. 数组的度
    【题目描述】给定一个非空且只包含非负数的整数数组 ​​nums​​,数组的 度 的定义是指数组里任一元素出现频数的最大值。你的任务是在 ​​nums​​​ 中找到与 ​​......
  • 【LeeCode】4. 寻找两个正序数组的中位数
    【题目描述】给定两个大小分别为 ​​m​​​ 和 ​​n​​​ 的正序(从小到大)数组 ​​nums1​​​ 和 ​​nums2​​。请你找出并返回这两个正序数组的 中位数 。......
  • 【LeeCode】17. 电话号码的字母组合
    【题目描述】给定一个仅包含数字 ​​2-9​​ 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。给出数字到字母的映射如下(与电话按键相同)。注意1不对......
  • 【LeeCode】53. 最大子数组和
    【题目描述】给你一个整数数组nums,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组是数组中的一个连续部分。​​​​https://leetcode.......
  • 【LeeCode】2488. 统计中位数为 K 的子数组 -- 太难了
    【题目描述】给你一个长度为n的数组nums,该数组由从1到n的不同整数组成。另给你一个正整数k。统计并返回num中的中位数等于k的非空子数组的数目。注意:数组......
  • 【LeeCode】栈和队列
    ​​学习参考​​【栈】importjava.util.*;//2022-12-15//栈:先进后出classMyStack{publicint[]elem;publicintuseSize;publicMyStack(){this......
  • 【LeeCode】链表的学习
    基础知识​​学习参考​​importjava.util.*;//JAVA链表classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;......
  • 【LeeCode】1832. 判断句子是否为全字母句
    【题目描述】全字母句指包含英语字母表中每个字母至少一次的句子。给你一个仅由小写英文字母组成的字符串sentence,请你判断sentence是否为全字母句。如果是,返回true......
  • 【LeeCode】392. 判断子序列
    【题目描述】给定字符串 s 和 t ,判断 s 是否为 t 的子序列。字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例......
  • 【LeeCode】剑指 Offer 42. 连续子数组的最大和
    【题目描述】输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)​​https://leetcode.cn/problems/lian-xu-zi-......