Javascript solution


  • 0
    K

    I found a pattern after writing out some binary numbers from 0 to 9
    if the number i is even, the number of 1's must be equal to the number of 1's at index i / 2
    if the number i is odd, the number of 1's must be equal to the previous number of 1's + 1

    /**

    • @param {number} num
    • @return {number[]}
      */
        var result = [0];
        for(var i = 1; i <= num; i++) {
            if(i % 2 === 0) {
               var index = i / 2;
               result.push(result[index]);
            }else {
               result.push(result[i - 1] + 1);
            }
        }
        return result;
    };
    

Log in to reply
 

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