leet_461(求汉明距离):
- leet_code:链接
- 问题描述:两个int型数的汉明距离就是它们二进制位中对应位不同值的个数。
- 输入输出样例:
- Input: x = 1, y = 4
Output: 2 - Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
- Input: x = 1, y = 4
- 代码说明:需要指出并记住的是:一个n与n-1按位与,相当于消除n对应二进制中最右边的1。
- c++代码:
#include<iostream>
using namespace std;
class Solution
{
public:
int hammingDistance(int x, int y)
{
int n = x^y, dst = 0;
while (n != 0)
{
++dst;
n &= (n - 1);
}
return dst;
}
};
int main(int argc, char* argv[])
{
int x = 8, y = 7;
Solution solution;
cout << solution.hammingDistance(x, y) << endl;
system("pause");
return 0;
}
leet_477(total hamming distance):
-
leet_code:链接
-
问题描述:
- 两个数字的汉明距离定义已经在上面介绍;
- 该题求解多个数字间的total汉明距离:所有数字相互求解汉明距离后的和。
-
输入输出样例:
-
Input: 4, 14, 2
Output: 6
-
解析: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
-
-
技巧解题关键:
- 4: 0 1 0 0
14: 1 1 1 0
2: 0 0 1 0
1: 0 0 0 1
我们先看最后一列,有三个0和一个1,那么它们之间相互的汉明距离就是3,即1和其他三个0分别的距离累加,然后在看第三列,
累加汉明距离为4,因为每个1都会跟两个0产生两个汉明距离,同理第二列也是4,第一列是3。
我们仔细观察累计汉明距离和0跟1的个数,我们可以发现其实就是0的个数乘以1的个数。
- 4: 0 1 0 0
-
具体参考:链接
-
c++ 代码:
#include<iostream>
using namespace std;
#include<vector>
class Solution
{
public:
int totalHammingDistance(vector<int>& nums)
{
int res = 0;
int* zeroOne = new int[2];
memset(zeroOne, 0, 2 * sizeof(int));
while(true)
{
int countZero = 0;
zeroOne[0] = 0;
zeroOne[1] = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 0)
++countZero;
zeroOne[nums[i] % 2]++;
nums[i] = nums[i] >> 1;
}
res += zeroOne[0] * zeroOne[1];
if (countZero == nums.size())
return res;
}
}
};
int main(int argc, char* argv[])
{
vector<int> nums = { 4, 14, 2 };
Solution solution;
cout << solution.totalHammingDistance(nums) << endl;
system("pause");
return 0;
}