website/content.en/ChapterFour/0400~0499/0477.Total-Hamming-Distance.md
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:
0 to 10^910^4.The Hamming distance between two integers refers to the number of positions at which the corresponding bits of their binary representations are different. Calculate the total Hamming distance between any two numbers in an array.
package leetcode
func totalHammingDistance(nums []int) int {
total, n := 0, len(nums)
for i := 0; i < 32; i++ {
bitCount := 0
for j := 0; j < n; j++ {
bitCount += (nums[j] >> uint(i)) & 1
}
total += bitCount * (n - bitCount)
}
return total
}
// Brute-force solution times out!
func totalHammingDistance1(nums []int) int {
res := 0
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
res += hammingDistance(nums[i], nums[j])
}
}
return res
}