[Medium]Counting Bits

来源:互联网 发布:socket异步收发数据 编辑:程序博客网 时间:2024/05/16 17:25

问题:
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.
解法:

源码:

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
原创粉丝点击