Skip to content

LeetCode题解:191. 位1的个数,位运算,JavaScript,详细注释 #336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Apr 30, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:191. 位1的个数

解题思路:

  1. 利用位运算n = n & (n - 1),每次可以清除二进制数中最后一个1。
  2. 每次循环进行上述操作,并统计1的数量,直到n被清零为止。
/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function (n) {
  let count = 0; // 统计1的数量

  // 不断循环直到1被清空
  while (n !== 0) {
    count++; // 每清除一个1就计数一次
    n = n & (n - 1); // 每次清除最后一位的1
  }

  return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant