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 ≤ xy < 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的数量累加起来就是汉明距离。

Java:

public int hammingDistance(int x, int y) {
int res = x ^ y;
int count = 0;
for (int i = 0; i < 32; i++) {
if ((res & 1) != 0)
count++;
res >>= 1;
}
return count;
}   

Python:

class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
distance = 0
z = x ^ y
while z:
distance += 1
z &= z - 1
return distance

Python:

class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1') 

C++:

class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
for (int i = 0; i < 32; ++i) {
if ((x & (1 << i)) ^ (y & (1 << i))) {
++res;
}
}
return res;
}
};

C++:  

class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
while (exc) {
++res;
exc &= (exc - 1);
}
return res;
}
};

C++:

class Solution {
public:
int hammingDistance(int x, int y) {
if ((x ^ y) == 0) return 0;
return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
}
};

  

类似题目:  

[LeetCode] 191. Number of 1 Bits 二进制数1的个数

All LeetCode Questions List 题目汇总

05-11 15:51