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.
汉明距离就是算两个二进制整数有多少位不同
&按位与,|按位或,^按位异或
要计算汉明距离,只用计算两数异或结果中1的个数
技巧:
把整数减一后的值与原值按位与,相当于把整数二进制中最右边的一个1变成0
//C++
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0;
int n = x ^ y;
while(n){
++dist;
n &= n-1;
}
return dist;
}
};
另外python中内置bin函数可以将整数转换为二进制字符串,然后用count函数统计字符串中1的个数也可以达到效果
#python
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')