[LeetCode] 191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three ‘1’ bits.

Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one ‘1’ bit.

Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one ‘1’ bits.

Constraints:
The input must be a binary string of length 32.
Follow up: If this function is called many times, how would you optimize it?

位1的个数。

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-1-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题意是给一个二进制的数字,求出其中1的个数。这题需要用到一个位运算的特性,建议背下来,就是 n & (n-1) 会让 n 最右边的 1 变为 0。所以只要记一个 count,然后看看这个 & 的操作做几次,数字整个变为 0,就说明过程中有几个 1 被变为 0 了。

复杂度

时间O(1) - 因为是位运算,再怎么样都只有32位
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
n &= n - 1;
res++;
}
return res;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
let res = 0;
while (n !== 0) {
n &= n - 1;
res++;
}
return res;
};

相关题目

1
2
191. Number of 1 Bits
2859. Sum of Values at Indices With K Set Bits

[LeetCode] 191. Number of 1 Bits
https://shurui91.github.io/posts/2691339022.html
Author
Aaron Liu
Posted on
October 15, 2019
Licensed under