https://en.wikipedia.org/wiki/Hamming_weight。
O(log(n)) 的解决方案,n 是位长
m1 = 0x5555555555555555 #binary: 0101...
m2 = 0x3333333333333333 #binary: 00110011..
m4 = 0x0f0f0f0f0f0f0f0f #binary: 4 zeros, 4 ones ...
m8 = 0x00ff00ff00ff00ff #binary: 8 zeros, 8 ones ...
m16 = 0x0000ffff0000ffff #binary: 16 zeros, 16 ones ...
m32 = 0x00000000ffffffff #binary: 32 zeros, 32 ones
h01 = 0x0101010101010101 #the sum of 256 to the power of 0,1,2,3...
def hammingWeight(self, x: int) -> int:
x -= (x>>1)&m1
x = (x&m2) + ((x>>2)&m2)
x = (x+(x>>4))&m4
return ((x*h01)>>56)&0x7f
而在 python 3.10 中,int 类型将有一个 bit_count() 方法