How to Create Total Hamming Distance in C++?

  C & C ++ Interview Q&A

Dear readers, today we read this tutorial on Total Hamming Distance in C ++?

If you have a list of numbers. We have to find the Hamming distance of all pairs of given numbers. We know that the Hamming distance between two integers is the number of terms on which the corresponding bits differ.

Example for Create Total Hamming Distance in C++

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const int m = 1e9 + 7;
class hammingDistance{
   public:
   lli add(lli a, lli b){
      return ((a % m) + (b % m));
   }
   lli mul(lli a, lli b){
      return ((a % m) * (b % m));
   }
   int cntBits(vector<int>& a){
      vector<vector<lli> > bits(32, vector<lli>(2));
      lli ans = 0;
      int n = a.size();
      for (int i = 0; i < n; i++) {
         lli x = a[i];
         for (lli j = 0; j < 32; j++) {
            lli b = (x >> j) & 1;
            ans = add(ans, mul((lli)1, bits[j][!b]));
            bits[j][b] = add(bits[j][b], (lli)1);
         }
      }
      return ans;
   }
   int totalHammingDistance(vector<int>& nums){
      return cntBits(nums);
   }
};
main(){
   hammingDistance ob;
   vector<int> v = {4,14,17,2};
   cout << (ob.totalHammingDistance(v));
}

Output

17

LEAVE A COMMENT