https://leetcode.com/problems/number-of-1-bits/
Difficulty: Easy
计算无符号整型中二进制1的数目
最直接的思路是判断每一位是否为1(可每次右移一位,直到n为0),为1则计数器增一。更好的方式为,每次消去一个1并计数
// Runtime: 4 ms
#include <cstdint>
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count++;
}
return count;
}
};
涉及到Hamming weight。在信息编码中,两个合法代码对应位上编码不同的位数称为码距,又称海明距离。对于二进制来说,海明距离的结果相当于 a XOR b 结果中1的个数。
维基百科给出了各种算法及分析,也给出了相应的代码。对于上述方法,当1很少时,效率还是很高的,但是在最坏情况下(均为1),需要循环32次。除上述方法外,还有两类方法。第一类是,在存储空间不受限时,可以建立一个lookup table,大小可以是2 ^ 16 = 65536
const uint8_t wordbits[65536] = { /* bitcounts of integers 0 through 65535, inclusive */ };
int popcount(uint32_t i)
{
return (wordbits[i&0xFFFF] + wordbits[i>>16]);
}
另一类可以保证最坏情况下的效率,也是对于这个问题的最佳实现方法。细节可以参考Efficient implementation,这里也把维基百科给出的例子引用过来。目标是计算 a = 0110 1100 1011 1010中的1的数目
Expression | Binary | Decimal | Comment |
---|---|---|---|
a | 0110 1100 1011 1010 | 原始数字 | |
b0 = (a >> 0) & 01 01 01 01 01 01 01 01 | 01 00 01 00 00 01 00 00 | 1,0,1,0,0,1,0,0 | |
b1 = (a >> 1) & 01 01 01 01 01 01 01 01 | 00 01 01 00 01 01 01 01 | 0,1,1,0,1,1,1,1 | |
c = b0 + b1 | 01 01 10 00 01 10 01 01 | 1,1,2,0,1,2,1,1 | a中每两位中1的数目 |
d0 = (c >> 0) & 0011 0011 0011 0011 | 0001 0000 0010 0001 | 1,0,2,1 | |
d2 = (c >> 2) & 0011 0011 0011 0011 | 0001 0010 0001 0001 | 1,2,1,1 | |
e = d0 + d2 | 0010 0010 0011 0010 | 2,2,3,2 | a中每四位中1的数目 |
思想很简单,所以,不再复制维基百科中后面的内容。另外还有两种优化的算法。
对于n = (n & 0x55555555) + (n >> 1 & 0x55555555);和n -= n >> 1 & 0x55555555;,显然它们是等价的,但是后者理解起来略让人费解,可以简单推导一下。记x = n & 0x55555555, y = n >> 1 & 0x55555555,需要证明x + y = a - y <==> a = x + 2y,考虑到2y的含义,即能理解其运算过程。
class Solution {
public:
// Runtime: 4 ms
// naive implementation
// It uses 24 arithmetic operations (shift, add, and).
int hammingWeight(uint32_t n) {
n = (n & 0x55555555) + (n >> 1 & 0x55555555); // 2
n = (n & 0x33333333) + (n >> 2 & 0x33333333); // 4
n = (n & 0x0f0f0f0f) + (n >> 4 & 0x0f0f0f0f); // 8
n = (n & 0x00ff00ff) + (n >> 8 & 0x00ff00ff); // 16
n = (n & 0x0000ffff) + (n >> 16 & 0x0000ffff); // 32
return n;
}
// Runtime: 4 ms
// implementation on machines with slow multiplication.
// It uses 16 arithmetic operations.
int hammingWeight(uint32_t n) {
n -= n >> 1 & 0x55555555;
n = (n & 0x33333333) + (n >> 2 & 0x33333333);
n = (n + (n >> 4)) & 0x0f0f0f0f;
n += n >> 8;
n += n >> 16;
return n & 0x3f; // 32 -- 10 0000
}
// Runtime: 8 ms
// implementation on machines with fast multiplication.
// It uses 12 arithmetic operations, one of which is a multiply.
int hammingWeight(uint32_t n) {
n -= n >> 1 & 0x55555555;
n = (n & 0x33333333) + (n >> 2 & 0x33333333);
n = (n + (n >> 4)) & 0x0f0f0f0f;
return (n * 0x01010101) >> 24;
}
};