Description
给定数组
Constraints
- 返回值必然在整型
int
范围内
Solution
按位处理贡献,每一位统计0和1的贡献
Code
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int res = 0;
for(int i = 31; ~i; --i) {
int bucket = 0;
for(auto n : nums) {
bucket += n >> i & 1;
}
res += bucket * (nums.size() - bucket);
}
return res;
}
};