C++ code based on the second hint


  • 0
    A
    class Solution {
    public:
        vector<int> countBits(int num) {
            assert(num>=0);
            vector<int>res;
            res.push_back(0);
            
            int index = 0;
            for(int interval = 1; ; interval *= 2)
            {
                for(int i=0;i<interval;++i)
                {
                    ++index;
                    if(index>num)
                        return res;
                        
                    int bitNum = res[index - interval] + 1;
                    res.push_back(bitNum);
                }
            }
    
        }
    };

Log in to reply
 

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