您的位置:首页 > 其它

Leetcode--Number of 1 Bits

2015-03-16 20:14 330 查看


Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
so the function should return 3.
思路:首先想到的是将比特位逐个右移,然后计算1的数量

具体代码如下:
int hammingWeight(uint32_t n) {
int res = 0;
while (n != 0){//当数字n不为0,或者是说当n中还有1的时候,一直循环
if(n %2 != 0)//判断n是否能够被2整除就是判断右移之后的n的末位是不是1,如果是1的话,计数器加1
++res;
n/=2;//n右移一位
}
return res;
}
还有一种相似的做法就是逐个对n的32比特位进行与的运算,然后算出1的数量
代码如下:
int hammingWeight(uint32_t n) {
int res = 0;
for (int i = 0; i < 32; ++i) {
res += (n & 1);//n&1 的意思就是判断n的末位是不是1,是1的话,结果为1,不是的话结果为0,然后再累加到res中
n = n >> 1;//n右移一位
}
return res;
}
但是这还是不够快,要循环32遍才能找出所有的1,如果能有多少个1循环多少遍,就是最快的方法。
举例来说:
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000

n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000

n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
由上可知,n&(n-1)能够把除了n和n-1中共有的1保留,其他的全部变0.由此写出代码:
<pre name="code" class="cpp">int hammingWeight(uint32_t n) {
int re = 0;
int left = 0;      
<span style="white-space:pre">	</span>while(0 != n)
<span style="white-space:pre">	</span>{
    <span style="white-space:pre">	</span>     n = n&(n - 1);
    <span style="white-space:pre">	</span>     ++re;
<span style="white-space:pre">	</span>}
}


这样便可做到有多少1循环多少遍。
参考文章:
点击打开链接

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