Problem:
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.
Solution 1:
(傻瓜法:把两个十进制数转化为二进制串,为了比较各个位是否相同,需要对较短的字符串补"0")
class Solution {
public:
int hammingDistance(int x, int y) {
string num1 = convertToBinary(x);
string num2 = convertToBinary(y);
return countDifferentBits(num1, num2);
}
string convertToBinary(int num) {
string str = "";
for (int i = num; i > 0; i /= 2) {
str += ((i % 2) ? '1' : '0');
}
reverse(str.begin(), str.end());
return str;
}
void modifyString(string& s, int n) {
string str = "";
for (int i = 0; i < n; i++) {
str += "0";
}
for (int i = 0; i < s.length(); i++) {
str += s[i];
}
s = str;
}
int countDifferentBits(string num1, string num2) {
int count = 0;
int len1 = num1.length();
int len2 = num2.length();
if (len1 < len2) modifyString(num1, len2-len1);
if (len2 < len1) modifyString(num2, len1-len2);
for (int i = 0; i < num1.length(); i++) {
if (num1[i] != num2[i]) {
count++;
}
}
return count;
}
};
Solution 2:
(利用异或操作:两个数作异或,相同的位则为0,不同则为1,得到的结果转化为二进制串,计算字符"1"的数目,即为所求
的海明距离)
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
string str = convertToBinary(z);
return countDifferentBits(str);
}
// 把十进制数转化成二进制字符串
string convertToBinary(int num) {
string str = "";
for (int i = num; i > 0; i /= 2) {
str += ((i % 2) ? '1' : '0');
}
reverse(str.begin(), str.end());
return str;
}
// 计算海明距离
int countDifferentBits(string num) {
int count = 0;
for (int i = 0; i < num.length(); i++) {
if (num[i] == '1') {
count++;
}
}
return count;
}
};
Solution 3 :
(解法出自:https://discuss.leetcode.com/topic/72236/my-c-solution-using-bit-manipulation)
(利用位运算:异或 + 与;首先求得两个数的异或,再通过与运算来计算海明距离)
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
Note:这里理解n &= n-1是一个难点,这个式子的作用是把n最右边的1转化为0,以此来统计异或结果中1的数目,即海明距离。