Use a mask bit, for each bit, count number of 1s (labeled as c) are there for all numbers in the array. Then the distance for this bit is c * (n - c). Iterate through all bits. You get the answer.

```
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int ans = 0, b = 1;
while (b) {
int c = 0;
for (int num : nums) {
if (num & b)
++c;
}
ans += c * (nums.size() - c);
b <<= 1;
}
return ans;
}
};
```