Javascript toString and array split count


  • 0
    J

    Cast the i value to its binary equivalent, then count the split of 1s.

    /**
     * @param {number} num
     * @return {number[]}
     */
    var countBits = function(num) {
        const res = [];
        
        for(let i = 0; i <= num; i++) {
            let thisBinary = i.toString(2);
            let count = thisBinary.split('1').length - 1;
            res.push(count)
        }
        
        return res;
    };

  • 0
    1

    Runtime of this sulution is not O(n).


Log in to reply
 

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