【LeeCode】338. 比特位计数

时间:2022-12-18 17:58:49

【题目描述】

给你一个整数 ​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;
}