Test case runs fine, but got MLE on submitting, anyone can help?


  • 0
    F
    /**
         * @param {number} num
         * @return {number[]}
         */
        var countBits = function(num) {
            var result=[0];
            var start=1;
            var curr =1;
            for(var i=1;i<=num;i++){
                if((i&(-i))===i){
                    result.push(1);
                    start=1;
                    curr=i;
                }
                else{
                    result.push(result[curr]+result[start]);
                    start++;
                }
            }
            return result;
        };

  • 0
    F

    I tried 123456 in the test case, it runs correctly but failed in submission.


  • 0
    I

    I had the same problem. Great solution by the way! Very clever with the i&-i check for powers of 2. One improvement could be removing the curr variable. Correct me if I'm wrong, but isn't result[curr] always going to equal 1? curr will only ever point to powers of 2 and you skipped the only case where a power of 2 has a number of 1s other than exactly one (0). Anyway, nice solution.


  • 0
    F

    I think this is the js issue, cuz I have converted the code to java and I got accepted. The 'curr' thing is that I just want to make the logic more clear. It's redundant ;). I think the better way is to have a 'const' here.


Log in to reply
 

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