自学内容网 自学内容网

【LeetCode 0191】【位运算】求1的个数

  1. Number of 1 Bits

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

Example 1:

**Input:** n = 11

Output: 3

Explanation:

The input binary string 1011 has a total of three set bits.

Example 2:

**Input:** n = 128

Output: 1

Explanation:

The input binary string 10000000 has a total of one set bit.

Example 3:

**Input:** n = 2147483645

Output: 30

Explanation:

The input binary string 1111111111111111111111111111101 has a total of thirty set bits.

Constraints:

  • 1 <= n&nbsp;<= 2^31&nbsp;- 1

Follow up: If this function is called many times, how would you optimize it?

JavaScript Solution
/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    let ans = 0;
    while(n != 0){
        n &= n-1;
        ans++;
    }
    return ans;
};

原文地址:https://blog.csdn.net/avenccssddnn/article/details/140540306

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!