My javascript solution. How can I improve this ?


  • 0
    J
    var hammingWeight = function(n) {
        n=n.toString(2);
        var count=0;
        for(var i=0;i<n.length;i++)
        {
            if(n[i]==='1')
                count++;
        }
        return count;
    };
    

    How can I improve this?


  • 1
    L

    Doing this in a loop: n = n & (n - 1)
    This code will execute only once when N is 1 or 10000000000000000000000000000000 (binary). You don't need to convert it to string.


Log in to reply
 

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