Simple and 4 lines


  • 19
    M
    class Solution {
    public:
        vector<int> countBits(int num) {
    
            vector<int> res(num+1,0);
           
            for(int i = 1; i < res.size();i++)
                res[i] = i%2 + res[i/2];
    
            return res;
        }
    };

  • 1
    N

    I like the answer. It makes lot of sense.
    I personally did it a bit cheaper way but a dynamic programming is better.
    Here is what I did in Python:

    class Solution(object):
        def countBits(self, num):
            """
            :type num: int
            :rtype: List[int]
            """
            arr = []
            for i in range(num+1):
                binary = bin(i)[2:]
                ones = binary.replace("0","")
                count = len(ones)
                arr.append(count)
            return arr

Log in to reply
 

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