C++ Solution : Bit Manipulation


#1
int Solution::hammingDistance(const vector<int> &A) {
long long n = A.size();
long long res = 0;
for(int i=0;i<32;i++){
    int count=0;
    for(int j=0;j<n;j++){
        if(A[j] & 1<<i)
            count++;
    }
    res += count * (n-count) *2;
    
}
return res % 1000000007;

}


#2

res is overflowing inside the for loop. There is a possibility that it will overflow inside the loop so use %1000000007 everywhere, there is possibility of overflow.


#3

Can u please explain how the if condition (A[j] & 1<<i) works?