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;
}
}