题干: 编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).)。
题解: 如果像十进制那样循环(cnt = n%2, n/=2),当n为负数的时候就会报错。这里可以用到与运算,n&1=1就说明最后一位是1,如果n&1=0就说明最后一位是0,判断完最后一位然后进行右移,需要注意的是有符号的右移是>>,无符号的右移是>>>
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int cnt=0;
while(n!=0){
int x = n&1;
if(x==1)cnt++;
n>>>=1;
}
return cnt;
}
}