Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.
解法1: 把每一位都 & 1, 计算所有1的个数
解法2: 因为n & (n - 1)就可以消除掉最右边的一个1, 比如110,减去1得101,相与得100,消去了最右边的1。这样一直消除到没有, 可以计算出1得个数
解法2: 因为n & (n - 1)就可以消除掉最右边的一个1, 比如110,减去1得101,相与得100,消去了最右边的1。这样一直消除到没有, 可以计算出1得个数
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++) {
if (((n >> i) & 1) == 1) {
count++;
}
}
return count;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
}
没有评论:
发表评论