Javascript Solution (with comment)


  • 0
    N
    var countBits = function(num) {
        var count = [1],
            res = [0, 1];
        for (var i = 1; i <= Math.log2(num); i++) { // divide array into groups based on pow of 2
            var secondHalf = count.map(function(val){ 
                return val + 1;
            }); // the second half of how many 1s in this group, the recursive formula is x[i] = x[i] concat result after increment 1 to each element in x[i]
            count = count.concat(secondHalf);
            res = res.concat(count);
        }
        
        return res.slice(0, num+1);
        
    };
    
    

Log in to reply
 

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