使用n&(n-1)的方法
只要不是全0 就打掉最后一个1 然后计数++
假使 n =0x110101
n n-1 n&(n-1)
step1: 110101 110100 110100
step2: 110100 110011 110000
step3: 110000 101111 100000
step4: 100000 011111 000000
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;
}
}
法二:
循环数有几个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%2!=0){
count++;
}
n=n>>1;
}
return count;
}
}