I participated in one algorithmic competition. I got stuck in one problem, I am asking the same here.
Problem Statement
XOR-sum array is to XOR
I think you left out some very important details:
int A[MAXN];// the arrays contain int values
//xor all the elements of the array as you read them
for (int i=1; i<=N; i++) {
scanf("%d", &A[i]);
A[i]^=A[i-1];
}
After reading the inputs you will end up with:
A[0] = A[0]
A[1] = A[1]^A[0]
...
A[N] = A[N]^A[N-1]^...^A[0]
This is O(N) an you get it for free basically since you have to read the input anyway. This takes care or the XOR part. Now you are left with only the SUM part of the problem. You have N int numbers (32bit), here is where the part you showed comes in:
for (int i=0, p=1; i<30; i++, p<<=1) {
int c=0;
for (int j=0; j<=N; j++) {
if (A[j]&p) c++;
}
ret+=(long long)c*(N-c+1)*p;
}
For each bit you go through the array and count the number of 1 and add them to the final result.
This part is O(30*N) which is still linear time so O(N). which is better than O(N^2).
Hope this sheds some light on the matter.