XOR property in 3 lines


#1

int Solution::singleNumber(const vector &A) {
int result=0;
for(int i=0;i<=A.size()-1;i++)
{
result=result^A[i];
}
return result;
}


#2

def singleNumber( self,A):
A = sorted(A)
i = 0
while i<len(A)-1:
if(A[i]==A[i+1]):
i+=2
else:
return A[i]
return A[len(A)-1]


#3

Above code runs good. but i am lil confused how XOR operator computes.
Ex. in every iteration it would produce weird result if result and A[i] is not same(i.e. result^A[i] won’t be zero). it might be some different number other than elements of array itself.
please clarify how XOR works on all element of array. is it one by one or in associative manner


#4

It is because of xor’s associative property. so, as A^(B^C)=(A^B)^C when a number is repeated it can be paired with itself.