题目
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:
For num = 5, you should return [0,1,1,2,1,2].
输入一个整数,输出一个数组,数组中的元素为从0到这个整数的每个数字的二进制中有多少个1。
思路
思路(来自 LeetCode 讨论区大佬 ):
1111 相比于 111 多了一个1,1110 相比于 111 ,1的个数相同,而 1111 或者 1110 右移一位得到111。
根据这个特性,只需要判断最后一位是不是1即可
代码
public int[] countBits(int num) {
if (num < 0) {
return null;
}
int[] res = new int[num + 1];
for (int i = 0; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}