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 < 2^{31}\).
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
思路:
Solution (C++):
int hammingDistance(int x, int y) {
vector<int> v1 = getBinary(x), v2 = getBinary(y);
int m = v1.size(), n = v2.size(), distance = 0;
while (n > m) {
v1.push_back(0);
m++;
}
while (m > n) {
v2.push_back(0);
n++;
}
for (int i = 0; i < m; ++i) {
if (v1[i] ^ v2[i]) distance++;
}
return distance;
}
vector<int> getBinary(int x) {
vector<int> v{};
if (x == 0) { v.push_back(0); return v; }
while (x) {
v.push_back(x%2);
x /= 2;
}
return v;
}
性能:
Runtime: 0 ms??Memory Usage: 6.3 MB
思路:
直接考虑按位异或。判断大数在2的多少幂之间可以求出对应的2进制位数。
Solution (C++):
性能:
Runtime: ms??Memory Usage: MB
原文:https://www.cnblogs.com/dysjtu1995/p/12609988.html