300ms JS solution for Elimination Game


  • 0
    E

    I can't find a better way to do this. If anyone have better idea, feel free to point it out :)
    The below idea is find loop times by Math.log2
    And init the result = 1, each step is Math.pow(2,i);
    Continue to get result+=step unless left = false && n%2===0.

    /**
     * @param {number} n
     * @return {number}
     */
    var lastRemaining = function(n) {
        var intloop = Math.floor(Math.log2(n));
        var left = true;
        var result=1;
        for (var i=0;i<=intloop-1;i++) {
            if(left || n%2===1 ){
                result+=Math.pow(2,i);
            }
            left=!left;
            n = Math.floor(n/2);
        }
        return result;
    };
    

Log in to reply
 

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