The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: 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.
Note:
1. Elements of the given array are in the range of 0 to 10^9
2. Length of the array will not exceed 10^4.
本题难度在leetcode上标记为medium,其实并不难,关键是不要被total迷惑住,把握住hamming distance的定义就好。
关于 hamming distance:两个数各二进制位置上的不同位个数的总和。
只求两个数的海明距离简单异或即可得到答案,本题只要把异或过程拆开即可求解,类似之前做过的一道题目,那道题是求一个数组里的两个不同数分别是多少,关键的一步是利用不同数的二进制表达的最低位开始的某一位不同(0和1),凭借这一位将数组分为两堆,分别异或求解。
对于本题:
要求任意两个数的海明距离,根据上面的分析,海明距离是不同位的个数求和,对于数组中数的每一位,我们都可以把它分成两组,一组该位是0 另一组为1,对于每一位的分别求解,就可以得到对于该位上所有数的海明距离之和,最后将各位求和结果再求和,就得到了最终解。
实现代码如下(C++11):
class Solution {
public:
int totalHammingDistance(vector& nums) {
int total = 0;
int size = nums.size();
for(int i = 0;i<32;i++) {
int count = 0;
for(auto&val:nums) {
if((val>>i)&1) count++;
}
total+= count*(size-count);
}
return total;
}
};
`