Total Hamming Distance

Total Hamming Distance

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.

Solution1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int totalHammingDistance(int[] nums) {
int length = nums.length;
if (length == 0 || nums == null) {
return 0;
}

int total = 0;
for (int i = 0; i < 32; i++) {
int bitCount = 0;
for (int j = 0; j < length; j++) {
if ((nums[j] & (1 << i)) != 0) {
bitCount++;
}
}
total += bitCount * (length - bitCount);
}
return total;
}