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.
这道题要求充分利用前面的结果,我们可以找到以下规律:
如果一个数是2的幂次,那么它1的个数就是1个
如果不是,那这个数可以拆成比他小的那个最大的2的幂次的和另一个数的和,1的个数也是这两个数中1的个数的和。其中2的幂次的1的个数永远为1,另一个数的1的个数已经计算过了。
比如14这个数,其二进制码为1110,拆成8+6,1000+0110。
/**
* @param {number} num
* @return {number[]}
*/
var countBits = function(num) {
var res=[];
res[0]=0;
var k=0;
for(var i=1;i<=num;i++){
if((i&(i-1))===0){
k=i;
res[i]=1;
}
else {
res[i]=1+res[i-k];
}
}
return res;
};
网友评论