您的位置:首页 > 其它

Number of 1 Bits问题及解法

2017-03-27 10:26 471 查看
问题描述:

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

示例:

the 32-bit integer ’11' has binary representation 
00000000000000000000000000001011
, so the function should return 3.

问题分析:

可根据向右移位与1按位与操作,可得‘1’的数目。

还有一种更高效的方式 : n = n &( n -1 )

过程详见代码:

按位与

class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t flag = 1;
int res = 0;
while(n)
{
res += (n & flag);
n = n >> 1;
}
return res;
}
};

更高效方式:
int hammingWeight(uint32_t n) {
int count = 0;

while (n) {
n &= (n - 1);
count++;
}

return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: