「刷刷刷」338. 比特位计数

题目

难度:中等

给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits

思路

参考 191. 位1的个数x & (x - 1) 会将 x 二进制末尾的 1 变为 0。
也就是说二进制的 x 一定比 x & (x - 1) 多一个 1。而且 x 一定比 x & (x - 1) 大。
那么按照题目所需用数组表示的话:num[i] = num[i (x-1)] + 1

代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] countBits(int num) {

int res[] = new int[num + 1];

for (int i = 1; i <= num; i++) {
res[i] = res[i & (i - 1)] + 1;
}

return res;
}
}

作者:prik
永久链接: https://trzoey.github.io/blog-prik/algorithmic/338.counting-bits/
转载请注明出处,谢谢合作💓。