C++ 9 lines O(n) time O(1) space


  • 0
    Z

    class Solution {
    public:

    vector<int> countBits(int num) {
        vector<int> ans;
        ans.push_back(0);
        int mark = 1;
        for (int i = 1; i <= num; i++) {
            ans.push_back(1+ans[i-mark]);
            if (i+1 == mark*2)
                mark *= 2;
        }
        return ans;
    }
    

    };


Log in to reply
 

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