Bus error in my solution


#1

My approach is that: we find the xor of the 2 numbers then convert the result into binary and find number of 1’s in the result. This would give us the number of bits different in the two number. For more efficiency, a 2d array is used in case the value is already calculated for 2 numbers such that dp[x][y] = dp[y][x] and dp[x][x] = 0. Also, ones array is used to store whether we already know the number of ones in the binary representation of the number. Why is my solution giving bus error? Solution is as follows:

int Solution::hammingDistance(const vector &A) {

int len = A.size();

if(len <= 1) return 0;

int max = 0;
for(int i=0; i<len; i++)
{
    if(A[i] > max) max = A[i];
}

const int len2 = max+1;
int dp[len2][len2];
//alternatively learn to use map
memset(dp, -1, sizeof(dp[0][0]) * len2 * len2); 


int tempNum = max;
int maxDigits = 0;
string binaryMax = "";
while(tempNum > 0)
{
    binaryMax = binaryMax + to_string(tempNum % 2);
    tempNum /= 2;
}

//reverse(binaryMax.begin(),binaryMax.end());
maxDigits = binaryMax.length();

//when all digits are 1
const int maxXOR = pow(2,maxDigits+1) - 1;
int ones[maxXOR+1];
memset(ones, -1, sizeof(ones)); 

ones[0] = 0;
ones[1] = 1;

long long int ans = 0;

for(int i=0; i<len; i++)
{
    for(int j=0; j<len;j++)
    {
        if(A[i] == A[j]) continue;
        if(dp[A[i]][A[j]] != -1)
        {
            ans += dp[A[i]][A[j]];
            if(ans > 1000000007) ans = ans%1000000007;
            continue;
        }
        if(dp[A[j]][A[i]] != -1)
        {
            dp[A[i]][A[j]] = dp[A[j]][A[i]];
            ans += dp[A[i]][A[j]];
            if(ans > 1000000007) ans = ans%1000000007;
            continue;
        }
        
        int temp = A[i] ^ A[j];
        if(ones[temp] == -1)
        {
            int noOfOnes = 0;
            string binaryNum = "";
            while(temp > 0)
            {
                binaryNum = binaryNum + to_string(temp % 2);
                temp /= 2;
            }
            //reverse(binaryNum.begin(),binaryNum.end())
            for(int k=0; k<binaryNum.length();k++)
            {
                if(binaryNum[k] == '1') noOfOnes++;    
            }
            
            dp[A[i]][A[j]] = noOfOnes;
            ans += noOfOnes;
            ones[temp] = noOfOnes;
            if(ans > 1000000007) ans = ans%1000000007;
        }
        else
        {
            dp[A[i]][A[j]] = ones[temp];
            ans += ones[temp];
            if(ans > 1000000007) ans = ans%1000000007;
        }
    }
}


return ans%1000000007;

}