您的位置:首页 > 编程语言 > C语言/C++

leetcode 191 Number of 1 Bits C++

2016-05-15 21:11 726 查看
这个一分钟搞定。

就是要对位运算有一定的了解

乘2相当于整体二进制位左移一位,而且这种运算方式比直接乘要快。

因此只要判断是奇数就加一,然后整体右移一位。

class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n){
if (n % 2 == 1) count++;
n = n>>1;
}
return count;
}
};


刚看到了一种更快的方式,直接与操作。

class Solution {
public:
int hammingWeight(uint32_t n)
{
int res = 0;
while(n)
{
n &= n - 1;
++ res;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: