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的个数(也被称作Hamming weight)
例如,32位的整数'11'的二进制表示为00000000000000000000000000001011,所以函数应该返回3。
还好计组中做过与位相关的实验。。。倒是没有什么难度,不过需要注意的是符号的运算顺序。。。
class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t temp=0x0001;
int sum=0;
while(n!=0)
{
if((temp&n)!=0) sum++;
n>>=1;
}
return sum;
}
};
这里提供一种百度到的方法。。。比我这种数1的个数的方法不知道高到哪里去了←_←
但是此种方法较慢,对于0x1ffffff的判定需要循环32次才能计算出结果,超时。
故转换思路,举例:
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中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,比第一种暴力枚举的解法要少很多次。最终实现代码如下,AC:
<code class="hljs cs has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><strong><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">class</span> Solution {
<span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// you need to treat n as an unsigned value</span>
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> <span class="hljs-title" style="box-sizing: border-box;">hammingWeight</span>(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> n) {
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> re = <span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span>;
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">while</span>(<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span> != n)
{
n = n&(n - <span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">1</span>);
++re;
}
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">return</span> re;
}
}</strong></code>