Single pass solution using cpp, easy to understand


  • 0
    P
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> ans(num+1,0);
            for(int i=1;i<=num;i+=2){
                if(i%2){
                    ans[i] = ans[i-1]+1;
                    for(int j=1;(i<<j)<=num;++j) ans[i<<j] = ans[i];
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

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