Take the XOR all the elements.
Steam will be canceled as
a XOR a = 0
and the result will be the only unpaired element as
0 XOR a = a
If everything is in order to destroy the array, you can XOR adjacent elements. After execution, the last element of the array has an unpaired element:
N = Num of elements in array. for( i=1 to N ) arr[i] ^= arr[i-1]; print arr[N-1]
If you cannot destroy the array, you can use the variable to store the result:
N = Num of elements in array. Unpaired = arr[0]; for( i=1 to N ) Unpaired = Unpaired ^ arr[i]; print Unpaired
C do the same:
int findUnpaired(int *arr,int len) { int i; // loop counter. int unpaired; // to hold the unpaired element. unpaired = arr[0]; // initialize it with the 1st array ele. for(i=1;i<len;i++) { // loop for all remaining elements. unpaired ^= arr[i]; // XOR each element with the running XOR. } return unpaired; // return result. }
codaddict Apr 15 '10 at 9:43 2010-04-15 09:43
source share