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 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [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.
题意:求一个数的二进制队列中有多少个1.
思路:
最笨的方法:将数拆分成二进制后,再逐个纪录1的个数。
简单的方法:原数/2等于将二进制队列向右移一位,如4/2=2 ( 100>>1 = 10)。
可见某数的二进制队列为此数除2后的二进制队列再加上0或1。
代码:
class Solution {
public int[] countBits(int num) {
int[] count = new int[num+1];
for(int i=1;i<=num;i++){
// 'x>>y'表示x的二进制右移y位,等于除以2^y;
// ‘z&1’表示z与1相与, 0&1=0,1&1=1, 2&1=0
count[i] = count[i>>1] + (i&1);
}
return count;
}
}

本文介绍了一种高效计算非负整数范围内每个数二进制表示中1的数量的方法。通过观察数的二进制表示,提出了一种线性时间复杂度的算法,避免了使用内置函数,实现了在单次遍历中完成计算。

被折叠的 条评论
为什么被折叠?



