题目
代码
法一:从右往左一次遍历查找1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0) {
if((n&1)==1) count++;
n = n >> 1 ;
}return count;
}
}
法二:当前数与比其小1的数与运算即消除一个1.以此计数。
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;
}
}