题目:
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].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
链接:https://leetcode.com/problems/counting-bits/
这道题的意思就是给一个非负数num,i在0到num之间,计算每个i整数二进制中1的个数。
思路:首先提出一个如果我们计算一个数二进制中1的个数,我们可以利用每个数和1求与判断是否等于1,在进行右移。这种方法计算的话我们的复杂度就不是O(n)了。我们可以分析,利用之前算出的结果我们也可以得到二进制1的个数。a[i]=a[i&(i-1)]+1,一个数减去1就是把该数的最右边第一个赋值为0,并且该1最右边均变成1和该数求交之后,意思就是计算比之前少个1的数然后就可以加1。
java代码如下
public class Solution {
public int[] countBits(int num) {
int[] a=new int[num+1];
for(int i=0;i<=num;i++){
if(i==0){
a[i]=0;
}
else{
a[i]=a[i&(i-1)]+1;
}
}
return a;
}
}