编写一个函数,输入是一个无符号整数(,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
示例 1:
输入:3
二进制格式:00000000000000000000000000001011
输出
3
代码设计:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
//题目描述问题 还是整数输入的
int count=0;
while(n!=0){
count+=n&1;//正确答案
// if(n%2==1)//Java采取这种方法不对 //11111111111111111111111111111101
// //count++;
n>>>=1;//无符号数 右移1位
}
return count;
}
}