Interesting point : bug or mistake


I wrapped my head for two hour to find the bug in the following code. This was partially accepted.

int mod = 1000000007;

int Solution::hammingDistance(const vector<int> &A) {
    int n = A.size();
    long long int count = 0;
    for(int i=0; i<31; i++){
        int ones = 0;
        for(int j=0; j<n; j++){
            if(A[j] & (1<<i)) ones++;
        // weirdness occured here
        count += (ones*(n-ones))*2;
        count = count%mod;
    return (int)count;

Interesting, if i changed n in count += (ones*(n-ones))*2 to A.size(), it got accepted. I don’t understand this weirdness.

If anyone do know the logic behind this, please share with me?


change type of ‘n’ to long long .