191. The number of bits 1

Answer:

  1. Bitwise operationn = n & (n - 1)The last 1 in the binary number can be cleared each time.
  2. Perform the above operations in each cycle and make statistics1The number ofnIs cleared to zero.
/ * * *@param {number} n - a positive integer
 * @return {number}* /
var hammingWeight = function (n) {
  let count = 0; // Count the number of 1s

  // Loop until 1 is empty
  while(n ! = =0) {
    count++; // Count every 1 cleared
    n = n & (n - 1); // Clear the last 1 each time
  }

  return count;
};
Copy the code