1
/*
2
So in the question we want to find out the
3
number of difference of bits between each pair
4
so in the brute force we will iterate over the vector
5
and for every pair we will calculate the Hamming distance
6
the Hamming distance will be calculated by taking XOR between the two elements
7
and then finding out the number of ones in the XOR of those two elements
8
the intuition behind this method is that XOR will contain 1's at those places
9
where the corresponding bits of elements x & y are different
10
therefore we will add this count
11
to our answer
12
*/
13
class Solution {
14
public:
15
int hammingDistance(int x, int y) {
16
int XOR = x ^ y;
17

18
int count = 0;
19
while (XOR) {
20
if (XOR & 1) count++;
21

22
XOR = XOR >> 1;
23
}
24
return count;
25
}
26

27
int totalHammingDistance(vector<int> &nums) {
28
int ans = 0;
29
for (int i = 0; i < nums.size() - 1; i++) {
30
for (int j = i + 1; j < nums.size(); j++) {
31
ans += hammingDistance(nums[i], nums[j]);
32
}
33
}
34

35
return ans;
36
}
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0