Total Hamming Distance in C++


Suppose we have a list of numbers. We have to find the Hamming distance of all pair of given numbers. We know that the Hamming distance between two integers is the number of positions at which the corresponding bits are different.

So, if the input is like [4,14,17,2], then the output will be 17.

To solve this, we will follow these steps −

  • m := 1^9 + 7

  • Define a function add(), this will take a, b,

  • return ((a mod m) + (b mod m))

  • Define a function mul(), this will take a, b,

  • return ((a mod m) * (b mod m))

  • Define a function cntBits(), this will take an array a,

  • Define one 2D array bits of size 32 x 2

  • ans := 0, n := size of a

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • x := a[i]

    • for initialize j := 0, when j < 32, update (increase j by 1), do −

      • b := (x / 2^j) AND 1

      • ans := add(ans, mul(1, bits[j, inverse of b]))

      • bits[j, b] := add(bits[j, b], 1)

  • return ans

  • From the main method do the following −

  • return cntBits(nums)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const int m = 1e9 + 7;
class Solution {
   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(){
   Solution ob;
   vector<int> v = {4,14,17,2};
   cout << (ob.totalHammingDistance(v));
}

Input

{4,14,17,2}

Output

17

Updated on: 05-Jun-2020

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements