[leetcode] 338. Counting Bits解題レポート


タイトルリンク:https://leetcode.com/problems/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.
Show Hint 
考え方:主に2進数の性質を考察する、すなわちA/2=Bであれば、AはBより1位多くなり、AとBがAを出した2進数の右の1位以外は同じで、栗A=11を挙げると、2進数は1011、B=5、2進数は101であるため、その最左が等しく、Aの最後の1位だけが等しくないことがわかる. 
A/2=Bの場合、Aがどれだけ1つあるかは、Bがどれだけ1つあるか、Aの最も右のビットのバイナリ数が0か1かに依存すると結論することができる.Aの一番右の人が1であれば、AはBより1つ多い.そうしないと、彼らは等しい1を持っている.
コードは次のとおりです.
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> vec(num+1, 0);
        for(int i =1; i <= num; i++)
            vec[i] = vec[i/2] + i%2;   
        return vec;
    }
};