My very easy to understand C++ O(n) solution.


  • 0
    N
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> res;
            if (num < 0) return res;
             res.push_back(0);
            if (num == 0)
                return res;
            res.push_back(1);
            if (num == 1)
                return res;
            int count = 1;
            int index = 1;
            while(count < num )
            {
                res.push_back(res[index] + 0);
                res.push_back(res[index] + 1);
                index++;
                count +=2;
            }
            if(count > num)
                res.pop_back();
            return res;    
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.