Not best but a little easier understanding C++ solution


  • 0
    E
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> ret(num+1, 0);
            int base = 2;
            for (int n=1; n<=num; ++n)
            {
                if (n == base)
                {
                    ret[n] = 1;
                    base *= 2;
                }
                else ret[n] = ret[n-(base>>1)]+1;
            }
            return ret;
        }
    };
    

Log in to reply
 

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