题目来源:力扣
题目描述:
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
============================================================
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
==============================================================
you need to treat n as an unsigned value
审题:
对于该问题, 我们可以对整数逐位移位, 判断每一位是否为1, 统计为1的位数.由于题目要求将整数n看作无符号整数, 因此我们在移位时需要使用无符号的移位方法.
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}
另一个更巧妙的方法是将n与n-1进行与运算, 比较n与n-1的二进制位可以发现, n最右侧的1对应n-1为0, 而往左的各位则相同, 因此将n与n-1进行或运算 可以将最右侧的1变为0;
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}