3 lines C++ code


  • 10
    G
    class Solution {
    public:
        vector<int> countBits(int num) 
        {
            vector<int> res(num+1,0);
            for(int i=1;i<=num;i++) res[i]=(i & 0x01)? (res[i>>1]+1) : res[i>>1];
            return res;
        }
    };

  • 0
    M

    Nice job! It is a clearer and more effective solution than mine.


  • 0
    E

    this is mine~

    public:
    vector<int> countBits(int num) {
        vector<int> count;
        count.push_back(0);
        for(int i = 1; i <= num; i++) {
            count.push_back(count[i >> 1] + (i & 1));
        }
        return count;
    }

Log in to reply
 

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