Leetcode 338. Counting Bits


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.

構想:注:題意ではライブラリ関数を使用できないことを説明するこの問題では0~numの各数を計算するバイナリに含まれる1の個数の計算であり、0のバイナリのうちの1は0であり、その後の計算では、2つの場合を考慮する:1)この値が2のべき乗である場合、バイナリには1つの1 2しか含まれていない)このビットが2のべき乗でない場合、バイナリのビット数=そのビット数より小さい、最も近い2のべき乗次数の1の個数+(このビット数値-このビット数より小さく、最も近い2のべき乗次数の数)の数の1の個数
具体的なコードは以下の通りです.
public class Solution {
    public int[] countBits(int num) {
        int[] result = new int[num+1];
        result[0] = 0;
        int flag = 0;//     2      
        int pow =1;
        for(int i = 1; i < num+1; i++){
            if(i == pow){
                pow *= 2;
                result[i] = 1;
                flag = i;
            }
            else{
                result[i] = result[flag]+ result[i-flag];
            }
        }
        return result;
    }
}