题目描述:
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
解题思路:
- 想着将二进制无符号整数转换成字符串
itoa()
,然后遍历找出1,但是在C++编程中,头文件stdlib
没有包含; - 善于利用位运算:
n&1
,n为二进制数,得到n的最低位的值; - 通过判断是否为1,之后将n>>1位赋值给n;
- 不断循环判断每一个数字是否为1。
class Solution {
public:
int hammingWeight(uint32_t n)
{
int num=0;
while (n>0)
{
if(n&1==1)
num++;
n=n>>1;
}
return num;
}
};
解题思路2:
- 采用
n&(n-1)
的表达式能将数字 n 的二进制表示中,最右边的 1 变成 0; - 例如:
101 & 100 => 100
和100 & 011 => 0
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
while (n != 0) {
n &= n-1;
ret ++;
}
return ret;
}
};