description
The Hamming distance between two integers is the number of positions where the corresponding bits are different.
Now your job is to find the total Hamming distance between all given pairs of numbers.
Description
1. The elements of a given array are in the range of 0 to 10^9.
2. The length of the array does not exceed 10^4.
Sample
- 例1:
输入: [4, 14, 2]
输出: 6
解释:在二进制表示中,4是0100,14是1110,2是0010(只是显示在这种情况下相关的四个位)。 所以答案是:
汉明距离(4,14) + 汉明距离(4,2) + 汉明距离(14,2) = 2 + 2 + 2 = 6。
- 例2:
输入: [2, 1, 0]
输出: 4
解释:在二进制表示中,2是10,1是01,0是00(只是显示在这种情况下相关的四个位)。 所以答案是:
汉明距离(2,1) + 汉明距离(1,0) + 汉明距离(2,0) = 2 + 1 + 1 = 4。
Parsing
Refer to 835. Hamming distance
totalHammingDistance = function (nums) {
var total = 0,n = nums.length;
for (var j = 0; j < 32; j++) {
var bitCount = 0;
for (var i = 0; i < n; i++) {
bitCount += (nums[i] >> j) & 1;
}
total += bitCount*(n - bitCount);
}
return total;
}