![]() |
VOOZH | about |
Given an integer array arr[], return the sum of Hamming distances between all the pairs of the integers in arr.
The Hamming distance between two integers is the number of bit positions at which the corresponding bits are different.
Note: The answer is guaranteed to fit within a 32-bit integer.
Examples:
Input: arr[] = [1, 14]
Output: 4
Explanation: Binary representations of 1 is 0001, 14 is 1110. The answer will be:
hammingDist(1, 14) = 4.Input: arr[] = [4, 14, 4, 14]
Output: 8
Explanation: Binary representations of 4 is 0100, 14 is 1110. The answer will be:
hammingDist(4, 14) + hammingDist(4, 4) + hammingDist(4, 14) + hammingDist(14, 4) + hammingDist(14, 14) + hammingDist(4, 14) = 2 + 0 + 2 + 2 + 0 + 2 = 8.
Table of Content
Iterate over all pairs using nested loops and compute the Hamming distance by comparing their bits. For each bit position, increment the count if the bits differ. Sum all such counts to obtain the total Hamming distance across all pairs.
8
Count the number of 1s at each bit position (0 to 31) across all numbers. For each bit, multiply the number of 1s with the number of 0s to get its contribution to the total Hamming distance.
8