You can separate the calculation to do one bit at a time.
For example, look at the rightmost bit of all the numbers in the array. Suppose that a
numbers have a rightmost 0-bit, and b
numbers have a 1-bit. Then out of the pairs, a*b
of them will have 1 in the rightmost bit of the XOR. This is because there are a*b
ways to choose one number that has a 0-bit and one that has a 1-bit. These bits will therefore contribute a*b
towards the total of all the XORs.
In general, when looking at the n
th bit (where the rightmost bit is the 0th), count how many numbers have 0 (call this an) and how many have 1 (call this bn). The contribution towards the final sum will be an*bn*2n. You need to do this for each bit and sum all these contributions together.
This can be done in O(kn) time, where k
is the number of bits in the given values.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…