Leetcode 477 Total Hamming Distance
#include <vector>
#include <intrin.h>
#include<nmmintrin.h>
using namespace std;
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
int count = 0;
while (z){
z = z &(z - 1);
count++;
}
return count;
}
int hammingDistance2(int x, int y){
int z = x ^y;
int count = __builtin_popcount(z);
return count;
}
int totalHammingDistance(vector<int>& nums) {
int totalHd = 0;
int size = nums.size();
for (int i = 0; i < size - 1; i++){
for (int j = i + 1; j < size; j++){
totalHd += hammingDistance(nums[i], nums[j]);
}
}
return totalHd;
}
};
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int totalHd = 0;
int size = nums.size();
for (int j = 0; j < 32; j++){
int bitCount = 0;
for (int i = 0; i < size; i++){
bitCount += (nums[i] >> j) & 1;
}
totalHd += bitCount * (size - bitCount);
}
return totalHd;
}
};