LeetCode刷题实战477:汉明距离总和
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.
示例
示例 1:
输入:nums = [4,14,2]
输出:6
解释:在二进制表示中,4 表示为 0100 ,14 表示为 1110 ,2表示为 0010 。(这样表示是为了体现后四位之间关系)
所以答案为:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6
示例 2:
输入:nums = [4,14,4]
输出:4
解题
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int cnt,ans=0;
for(int i=0;i<32;i++){
cnt=0;
for(int j=0;jif(nums[j]&1){
cnt++;
}
nums[j]>>=1;
}
ans+=cnt*(nums.size()-cnt);
}
return ans;
}
};
LeetCode刷题实战462:最少移动次数使数组元素相等 II
LeetCode刷题实战470:用 Rand7() 实现 Rand10()