Method one: binary operation

var hammingWeight = function(n) {
    let res = 0;
    for (let i = 0; i < 32; i++) {
        if ((n & (1<< i)) ! = =0) {  // Use a binary number with only one bit of 1 and n and
            res++;                   // is not equal to 0, i.e. 1, so res++}}return res;
};
Copy the code

Time complexity -> O(n)

Method two: bit operation optimization

The existence operation n&(n-1) is exactly the result of changing the least significant 1 in n to 0.

Example: 6&(6-1)= 4,6 = 110,4 =100, if n&(n-1) operation until n is 0, the number of operations is equal to the number of 1

var hammingWeight = function(n) {
    let res = 0;
    while (n) {
        n &= n - 1;
        res++;
    }
    return res;
};
Copy the code

Time complexity -> O(logn)