问题描述:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation00000000000000000000000000001011
, so the function should return 3.
《编程之美》P120
较为传统的解法一:使用将n不断右移,并与1想&得到1的个数;(也有使用除法/2的,明显除法的运行效率要低于位移)
时间复杂度:0(logn)
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
if(n & 1)
{
++count;
}
n >>= 1;
}
return count;
}
};
Java解法:
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count ++;
}
return count;
}
}
解法二:
使用n&(n-1)的方法
假使 n =0x110101
n n-1 n&(n-1)
step1: 110101 110100 110100
step2: 110100 110011 110000
step3: 110000 101111 100000
step4: 100000 011111 000000
发现有几个1,就循环几次n&(n-1)得到0,明显较于上者运行效率更高些。
时间复杂度:O(M),M是n中1的个数
故有代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
n &= (n-1);
++ count;
}
return count;
}
};
在频繁使用该算法的应用中,可以采用空间换时间的做法 ,但存储数组量级在2^32上,故一般不可取。
使用位运算可以获得更优的解法:
int count_ones(unsigned a)
{
a = (a & 0x55555555) + ((a >> 1) & 0x55555555);
a = (a & 0x33333333) + ((a >> 2) & 0x33333333);
a = (a & 0x0f0f0f0f) + ((a >> 4) & 0x0f0f0f0f);
a = (a & 0x00ff00ff) + ((a >> 8) & 0x00ff00ff);
a = (a & 0x0000ffff) + ((a >> 16) & 0x0000ffff);
return a;
}
int Count(unsigned n) {
unsigned temp;
temp = (n >> 1) & 033333333333;//注意此为八进制
n = n - temp;
temp = (temp >> 1) & 033333333333;
n = n - temp;
n = (n + (n >> 3)) & 030707070707;
n %= 63;
return n;
}
http://www.cnblogs.com/stoneJin/archive/2011/10/26/2224900.html
http://blog.csdn.net/justpub/article/details/2292823