The Hamming distance between two integers isthenumberof positions at which the corresponding bits are different.
Now your job isto find the total Hamming distance between all pairs ofthegiven numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the4is0100, 14is1110, and2is0010 (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:
Elements ofthegiven array are inthe range of0to10^9
Length ofthe array will not exceed 10^4.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
3 AC解
publicclassSolution {/**
*int长度是32bit,一共n个数
* 在每个位置上,如果有k个数为1,那么就有n-k个为0
* 那么贡献的海明距离就贡献了 k*(n-k) * 0x开头在java中表示16进制数, 0开头的话代表是8进制数,此处也可直接写1
* */publicinttotalHammingDistance(int[] nums) {
int total = 0;
int n = nums.length;
for (int i=0;i<32;i++){
int counter = 0;
for ( int j=0;j<n;j++){
counter += (nums[j] >> i) & 0x01;/*也可以这样写 int temp = nums[j] >> i;
if((temp&1)!=0){
counter ++;
}*/
}
total += counter*(n - counter);
}
return total;
}
}