Skip to content

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

@chencl1986

Description

@chencl1986

原题链接: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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions