461. Hamming Distance
class Solution: def hammingDistance(self, x: int, y: int) -> int: z = x^y z = (z&0x55555555)+((z>>1)&0x55555555) z = (z&0x33333333)+((z>>2)&0x33333333) z = (z&0x0f0f0f0f)+((z>>4)&0x0f0f0f0f) z = (z&0x00ff00ff)+((z>>8)&0x00ff00ff) z = (z&0x0000ffff)+((z>>16)&0x0000ffff) return z
48ms,13.2M
优化一:
class Solution: def hammingDistance(self, x: int, y: int) -> int: return bin(x^y).count('1')
40ms,13.3M
计算一个数中bit1的个数,采用合并计数器法 Parallel Counter
unsigned numbits(unsigned int i)
{
unsigned int const MASK1 = 0x55555555;
unsigned int const MASK2 = 0x33333333;
unsigned int const MASK4 = 0x0f0f0f0f;
unsigned int const MASK8 = 0x00ff00ff;
unsigned int const MASK16 = 0x0000ffff;
/*
MASK1 = 01010101010101010101010101010101
MASK2 = 00110011001100110011001100110011
MASK4 = 00001111000011110000111100001111
MASK8 = 00000000111111110000000011111111
MASK16 = 00000000000000001111111111111111
*/
i = (i&MASK1 ) + (i>>1 &MASK1 );
i = (i&MASK2 ) + (i>>2 &MASK2 );
i = (i&MASK4 ) + (i>>4 &MASK4 );
i = (i&MASK8 ) + (i>>8 &MASK8 );
i = (i&MASK16) + (i>>16&MASK16);
return i;
}
这个算法是一种合并计数器的策略。把输入数的32Bit当作32个计数器,代表每一位的1个数。然后合并相邻的2个“计数器”,使i成为16个计数器,每个计数器的值就是这2个Bit的1的个数;继续合并相邻的2个“计数器“,使i成为8个计数器,每个计数器的值就是4个Bit的1的个数。。依次类推,直到将i变成一个计数器,那么它的值就是32Bit的i中值为1的Bit的个数。
举个例子,假设输入的i值为10010111011111010101101110101111(十进制2541575087)
计算过程如下:(共22个1)
1. 将32个计数器合并为16个,每一个计数器代表 2-bit 的1个数
1 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 = 1 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1
+0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 = 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1
----------------------------------------------------------------------
1 1 1 2 1 2 2 1 1 1 1 2 1 1 2 2 = 01 01 01 10 01 10 10 01 01 01 01 10 01 01 10 10
2. 将16个计数器合并为8个,每一个计数器代表 4-bit 的1个数
1 1 1 2 1 1 1 2 = 01 01 01 10 01 01 01 10
+1 2 2 1 1 2 1 2 = 01 10 10 01 01 10 01 10
--------------- ---------------------------------------
2 3 3 3 2 3 2 4 = 0010 0011 0011 0011 0010 0011 0010 0100
3. 将8个计数器合并为4个,每一个计数器代表 8-bit 的1个数
3 3 3 4 = 0010 0011 0010 0010
+2 3 2 2 = 0011 0011 0011 0100
------- -----------------------------------
5 6 5 6 = 00000101 00000110 00000101 00000110
4. 将4个计数器合并为2个,每一个计数器代表 16-bit 的1个数
5 5 = 00000101 00000101
+ 6 6 = 00000110 00000110
----- ---------------------------------
11 11 = 0000000000001011 0000000000001011
5. 最后,将2个计数器合并为1个,每一个计数器代表 32-bit (也就是输入的值i)的1个数
11 = 0000000000001011
+11 = 0000000000001011
-- --------------------------------
22 = 00000000000000000000000000010110