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.
题解
一刷:
这道题给我们一个整数n,然我们统计从0到n每个数的二进制写法的1的个数,存入一个一维数组中返回。
规律是,从1开始,遇到偶数时,其1的个数和该偶数除以2得到的数字的1的个数相同,遇到奇数时,res[i] = res[i-1] + 1 或者res[i/2]+1 (因为i-1为偶数)
public class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
if(num == 0) return res;
res[0] = 0;
res[1] = 1;
for(int i=1; i<=num; i++){
if(i%2 == 0) res[i] = res[i/2];
else res[i] = res[i-1] + 1;
// or res[i] = res[i/2] + 1;
}
return res;
}
}
二刷
dynamic programming
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
if(num == 0) return res;
res[0] = 0;
res[1] = 1;
for(int i=2; i<=num; i++){
if((i&1) == 1) res[i] = res[i-1] + 1;
else res[i] = res[i/2];
}
return res;
}
}