Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Note:
- Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer 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 above the input represents the signed integer
-3.
Follow up:
If this function is called many times, how would you optimize it?
给定一个无符号的整数, 返回其用二进制表式的时候的1的个数。
n & (n - 1) 可以消除 n 最后的一个1。
这样我们可以不断进行n = n & (n - 1)直到n === 0 , 说明没有一个1了。 这个时候我们消除了多少1变成一个1都没有了, 就说明n有多少个1了。
//java
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 & (n - 1);
res++;
}
return res;
}
}
本文介绍了一种高效算法,用于计算给定无符号整数在二进制表示下1的个数,即汉明重量。通过n&(n-1)操作消除最后一位1,直至n为0,计数器记录消除次数即为1的数量。

被折叠的 条评论
为什么被折叠?



