Easiest C++ solution with step by step explanation. 0(n)


#1
int Solution::hammingDistance(const vector<int> &A) {
    int mod=1000000007;
    // lets use bitwise operators to calculate the hamming distance
    // when looking at the level of bit we will realise that bit at some specific has some 
    //contribution to the total distance
    // lets figure it out
    // we could only get a distance if there is difference in bits .
    // so what we would do is that we will calculate no of setbits at each position 
    int  n=A.size();
    long int mask= 1L<<31, ans=0;
    for(int i=0; i<=31; i++){
        long int  count=0;
        for(int  i=0; i< n; i++){
            if(A[i]&mask) count++;  // if setbit then we'll increment count
        }
        mask>>=1;
        ans+=(((n-count)*count)%mod); // taking one of set and one of unsetbit
         
    }
    ans=(ans*2)%mod;// because (4,6) AND (6,4) are taken as different bits here
    return (int)ans;
}

#2

yet this answer is giving partial correct remark ; not passing bigger test cases


#3

well!! actually this was my first post. And somehow i removed long before count while posting.
you can just make count as long int, to pass all cases.

int Solution::hammingDistance(const vector<int> &A) {
    int mod=1000000007;
    // lets use bitwise operators to calculate the hamming distance
    // when looking at the level of bit we will realise that bit at some specific has some 
    //contribution to the total distance
    // lets figure it out
    // we could only get a distance if there is difference in bits .
    // so what we would do is that we will calculate no of setbits at each position 
    int  n=A.size();
    long int mask= 1L<<31, ans=0;
    for(int i=0; i<=31; i++){
        long int  count=0;
        for(int  i=0; i< n; i++){
            if(A[i]&mask) count++;  // if setbit then we'll increment count
        }
        mask>>=1;
        ans+=(((n-count)*count)%mod); // taking one of set and one of unsetbit
         
    }
    ans=(ans*2)%mod;// because (4,6) AND (6,4) are taken as different bits here
    return (int)ans;
}