website/content/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.两个整数的汉明距离指的是这两个数字的二进制数对应位不同的数量。计算一个数组中,任意两个数之间汉明距离的总和。
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
}
// 暴力解法超时!
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
}