Cute lovely simple C++ solution


  • 14
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> r;
            r.push_back(0);
            for (int i=1;i<=num;i++){
                int x = r[i/2]+ (i%2);
                r.push_back(x);
            }
            return r;
        }
    };
    

    Because for an integer i, when i/2 equals to the bit representation of i shift right for one bit.
    So it's r[i/2]. And we just need to add i%2 which is the most right hand side of the bit set.


Log in to reply
 

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