题目描述:链接
解题思路:
- 利用计算汉明距离的那题,暴力求解(leetcode中超时)
- 好的方法进一步讨论中
class Solution {
public:
int hammingDistance(int x, int y)
{
//两个数异或,为1表示原来的两个数对应的二进制位不同,只需统计异或结果中1的个数
int z = x^y;
int count = 0;
while(z)
{
count++;
// z & (z - 1)每一次可以记一个1
z = z & (z - 1);
}
return count;
}
int totalHammingDistance(vector<int>& nums)
{
int total = 0;
for(int i = 0; i < nums.size(); ++i)
{
for(int j = i + 1; j < nums.size(); ++j)
{
total += hammingDistance(nums[i], nums[j]);
}
}
return total;
}
};