338 Counting Bits Bit bit count

Given a non-negative integer num. For each number i in the range 0 ≤ i ≤ num, count the number of 1s in its binary numbers and return them as an array.
Example:
For example, given num = 5, it should return [0,1,1,2,1,2].
Advanced: It
    is very easy to give a solution with time complexity of O(n * sizeof(integer)). But can you do it with one traversal in linear time O(n)?
    The space complexity of the algorithm is required to be O(n).
    Can you refine the solution further? Do this without using any built-in functions (like __builtin_popcount in c++) in c++ or any other language.
See: https://leetcode.com/problems/counting-bits/description/

C++:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> res(num+1,0);
        for(int i=1;i<=num;++i)
        {
            res[i]=res[i&(i-1)]+1;
        }
        return res;
    }
};

 Reference: https://www.cnblogs.com/grandyang/p/5294255.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324445773&siteId=291194637
Bit
BIT