Js:three ways to solve


  • 0
    Z
        var hammingWeight = function(n) {
        var count = 0;
        while(n){
            if(n & 1==1){
                count++;
            }
            n = n>>>1;
        }
        return count;
    };
    
    var hammingWeight = function(n) {
        var count = 0;
        while(n){
            n &= n-1;
            count++;
        }
        return count;
    };
    
    var hammingWeight = function(n) {
        var count = 0;
        while(n){
            n = (n&(-n))^n;
            count++;
        }
        return count;
    };

Log in to reply
 

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