【LeeCode】338. 比特位计数

【题目描述】

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

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

【示例】

【代码】adminInteger.toBinaryString(i); // 十进制转二进制Integer.bitCount(i) // 统计二进制中1的数量import java.math.BigInteger;import java.util.*;import java.util.regex.Pattern;// 2022-12-17class 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); }}

【代码】Officalpublic 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;}

伟人所达到并保持着的高处,并不是一飞就到的,

【LeeCode】338. 比特位计数

相关文章:

你感兴趣的文章:

标签云: