338. Counting Bits

来源:互联网 发布:北邮网络教育登录系统 编辑:程序博客网 时间:2024/06/05 06:38

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 timeO(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.

Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

分析:

写出几个可以发现,后边的都是以2为幂的步长网上加一。

所有先求出小于num的最小二次幂,这部分按递归累加。

后半部分也是累加,只是更简单一点。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> v1{0};
        if(num==0) return v1;
        v1.push_back(1);
        if(num==1) return v1;
        int p=2;
        int i=0;
        while(num>=p)
        {
            ++i;
            p=p*2;
        }
        p=p/2;
        for(int j=0;j<i-1;++j)
        {
            int len =v1.size();
            for(int t=0;t<len;++t)
            {
                v1.push_back(v1[t]+1);
            }
        }
        for(int t=0; t<=(num-p);++t)
         v1.push_back(v1[t]+1);
        return v1;
    }
};

0 0
原创粉丝点击