示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '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>>=1;
}
return count;
// //一般for循环方法
// String str = Integer.toBinaryString(n);
// int count = 0;
// for(int i=0; i<str.length();i++)
// {
// if(str.charAt(i)=='1')
// count++;
// }
// return count;
}
}