**Key observation:** Total Hamming distance can be decomposed into contributions from each bit position, and we calculate each of them independently.

Consider each 32-bit integer `x`

_{m=1:N} as a 32D 0-1 vector: e.g.,

`x`

_{1}: [1, 1, 0, 0, 1, ..., 0, 1]

`x`

_{2}: [0, 1, 0, 0, 1, ..., 0, 0]

`x`

_{3}: [0, 0, 1, 0, 0, ..., 0, 1]

...

`x`

_{N}: [1, 0, 0, 0, 1, ..., 1, 1].

For each "column" `i`

(i.e., `i`

-position bit), we count the number of `1`

bits `ones`

_{i}, then the contribution Hamming distance from `i`

-position bit is simply

`ones`

_{i}*(`N - ones`

_{i}).

Sum up all position `i`

and we have the answer Σ_{i=1:32}`ones`

_{i}*(`N - ones`

_{i}). The times complexity is O(8N sizeof(`int`

)).

```
int totalHammingDistance(vector<int>& nums) {
int res = 0;
for (int i = 1, ones = 0; (ones = 0), i; i<<=1) {
for (int n:nums) if (n&i) ++ones;
res += ones*(nums.size()-ones);
}
return res;
}
```