The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
求两个二进制数之间相差的位数。先用异或计算中间结果A,再求A中包含的1的个数。
求A中包含的个数,可用以下方法计算:
A = A & (A-1) 可将A最右侧的一个1变成0,因为A和A-1之间从最低位到A的最右一个1之间的各位都不同的,而最高位到A的最右一个1之间各位都是相同的,做AND运算之后即可清除最右的1。
执行一次上式,可清除一个1,累计执行的次数,直到A==0。
参考:https://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html
int hammingDistance(int x, int y) {
int z = x xor y;
int c;
for (c=0;z>0;c++)
{
z = z&(z-1);
}
return c;
}