C++ O(n) solution 79ms


  • 0
    S
    class Solution{
    public:
          vector<int> countBits(int num){
                vector<int> res={0};
                long long int base=1;
                int count=0;
                for(int i=1;i<=num;i++){
                     res.push_back(res[i-base]+1);
                     if(++count==base){
                           base*=2;
                           count=0;
                     }
                }
                return res;
          }
     };

Log in to reply
 

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