题目描述
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.
解题思路
题目直接求解很简单,但是题目要求时间复杂度为O(n),如果直接计算每个数字的二进制中1的个数肯定超过这个要求了。
首先可以很清楚的看出,f(0) = 0 以及f(1) = 1 。当要求2的二进制中1的个数的时候,考虑到2的二进制是10其实就是1左移了一位(乘2),同理4:100,是2(10)左移了一位。以此类推,可以得到偶数的1的个数 = 它除以2的结果中1的个数。
现在考虑奇数,2和3的区别就是在于最低位不同,只需要加上1即可。
注意可以使用位运算来提高运行速度。
代码实现
class Solution {
public int[] countBits(int num) {
int [] res = new int[num+1];
if(num == 0) {
res[0] = 0;
return res;
}
if(num >= 1) {
res[0] = 0;
res[1] = 1;
}
for(int i = 2; i < num + 1; i++) {
res[i] = res[i>>1] + (i&1);
}
return res;
}
}