6 line C++ O(N) solution beats 98.12% C++ submission


  • 0

    Just manually test first a few bits in numbers and you will find that the sequence will start with 0, and then just duplicate all previous bits with 1 added:
    E.G., 0 -> 0+1 = 1;
    {0, 1} -> { 1, 2 }
    {0, 1, 1, 2} -> {1, 2, 2, 3}, etc

        vector<int> countBits(int n) {
            vector<int> res = {0};
            while (res.size() < n+1) {
                int sz = res.size(), i = 0;
                while (i < sz && res.size() < n+1)  res.push_back(res[i++]+1);               
            }
            return res;
        }
    

Log in to reply
 

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