[Medium] Counting Bits

来源:互联网 发布:mac在哪里新建文件夹 编辑:程序博客网 时间:2024/06/05 03:14

【问题】

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~2^n-1这2^n个数组成的数列a[],可以知道,前2^(n-1)个数的最低(n-1)位,与后2^(n-1)个数(n-1)位具有相同的发展规律,不同的是前2^(n-1)个数最高位是0,后2^(n-1)个数最高位为1.

由此,可以知道,对于从0~2^n-1这2^n个数组成的数列,取i=2^(n-1),2^(n-1)+1,...,2^n - 1。对于第i个数a[i],其‘1’的个数是第i-2^(n-1)个数a[i-2^(n-1)]加一。这两个数的区别仅在于最高位,前者为1,后者为0.

【源码】

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> res;
        int n = 2;
        res.clear();
        res.push_back(0);
        res.push_back(1);
        while (n - 1 < num) {
            for (int i = 0; i < n; ++i) {
                res.push_back(res[i] + 1);
            }
            n = n * 2;
        }
        res.resize(num + 1);
        return res;
    }
};

0 0
原创粉丝点击