Problem 355
Total Hamming Distance
Medium · 20 pts · Array, Bit Manipulation, Math
Problem
The Hamming distance of two numbers is the number of bit positions where they differ. Given an array, add up the Hamming distances of every pair of positions (i, j) with i < j. Comparing every pair is O(N²); instead, look at each bit position separately: if c numbers have that bit set and N - c do not, that bit contributes c · (N - c) to the total.
Input
First line: N. Second line: N non-negative integers.
Output
Print the total Hamming distance over all pairs.
Constraints
1 <= N <= 100000; 0 <= A[i] <= 1000000000
Example input
3 4 14 2
Example output
6
Explanation
For 4 14 2 (binary 0100, 1110, 0010), the pair distances are 2 (4 vs 14), 2 (4 vs 2) and 2 (14 vs 2), giving a total of 6.