O(n) solution using bitwise operators


#1

int Solution::hammingDistance(const vector &A) {
int i , j , n = A.size() , sum = 0 , one = 0 , zero = 0 ;
int mod = 1000000007;
for ( i = 0 ; i < 32 ; i++)
{
one = 0 , zero =0 ;
for( j =0 ; j < n ; j++)
{
if(A[j]&(1<<i)) one++; // counting number of 1 at i-th position
else zero++; // counting number of 0 at i-th position
}
sum+=(2LLonezero)%mod; // for i-th position value of hamming distance
sum=sum%mod;
}
return sum;
}