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.

 

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

 

 

解题思路:

我们可以先观察一下数字的二进制形式:

0 --------->0

1 ---------> 1

2 ---------> 10

3 ---------> 11

4 ---------> 100

5---------->1001

 

二进制为逢二进一,当当前数字全部为1时,再往前一位变为1.

其实观察上面的形式我们可以发现:

  当进位后,重复进位前的过程直至再次进一产生新的1。

所以我们可以不断循环当前的ret数组,对ret数组内的值+1后然后加入ret数组尾部。

这里的count代表的时即将计算的数字,所以count == num时,num的值还没有加入

当count > num时,此时已经加入。

 

时间复杂度为O(n)

空间复杂度为O(n)

代码:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret;
        ret.push_back(0);
        if(num == 0)
            return ret;
        ret.push_back(1);
        int count = 2;
        while(count <=  num){
            int last_end = ret.size();
            for(int j = 0; j < last_end; j++){
                ret.push_back(ret[j] + 1);
                count++;
                if(count > num)
                    break;
            }
        }
        return ret;
    }
};

 

posted @ 2018-06-23 02:27  妖域大都督  阅读(87)  评论(0编辑  收藏  举报