Input:
nums = [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).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Instead of comparing every pair, we count for each bit position how many numbers have a 1 and how many have a 0. Each pair with different bits at that position contributes 1 to the total Hamming distance.
classSolution {
public:int totalHammingDistance(vector<int>& nums) {
int ans =0, n = nums.size();
for (int i =0; i <32; ++i) {
int cnt1 =0;
for (int x : nums) cnt1 += (x >> i) &1;
ans += cnt1 * (n - cnt1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
functotalHammingDistance(nums []int) int {
ans, n:=0, len(nums)
fori:=0; i < 32; i++ {
cnt1:=0for_, x:=rangenums {
if (x>>i)&1==1 {
cnt1++ }
}
ans+=cnt1* (n-cnt1)
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicinttotalHammingDistance(int[] nums) {
int ans = 0, n = nums.length;
for (int i = 0; i < 32; i++) {
int cnt1 = 0;
for (int x : nums) cnt1 += (x >> i) & 1;
ans += cnt1 * (n - cnt1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funtotalHammingDistance(nums: IntArray): Int {
var ans = 0val n = nums.size
for (i in0 until 32) {
var cnt1 = 0for (x in nums) cnt1 += (x shr i) and 1 ans += cnt1 * (n - cnt1)
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
deftotalHammingDistance(self, nums: list[int]) -> int:
ans =0 n = len(nums)
for i in range(32):
cnt1 = sum((x >> i) &1for x in nums)
ans += cnt1 * (n - cnt1)
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfntotal_hamming_distance(nums: Vec<i32>) -> i32 {
letmut ans =0;
let n = nums.len() asi32;
for i in0..32 {
let cnt1 = nums.iter().filter(|&&x| (x >> i) &1==1).count() asi32;
ans += cnt1 * (n - cnt1);
}
ans
}
}