JAVA - How does the bitwise exclusive OR assignment operator work in this given solution

Bryan Mcneil :

I recently was doing some coding challenges and this was one of the problems.

A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. Find the unpaired value. For example, given array A: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7.

After finishing my own, I came across this solution.

public int solution(int[] A) {
  int r = 0;
  for(int i=0;i<A.length;i++)
    r ^=A[i];

  return r;
}

I was amazed at this code. I have never seen the exclusive OR assignment operator before and was wondering how this solution works. If someone could walk me through this simple code and explain how it works that would be wonderful.

Adrian Shum :

In brief, A ^ B ^ B will give you back A. The two ^Bs does not need to be consecutive: As long as you have XORed same value twice, it clear out the effect. In your question, as values are in pairs, so normally same value will be XORed twice, which gives no effect in the final value, except that un-paired value. So the final result will simply be 0 ^ thatUnPairedValue, which is simply thatUnPairedValue.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460653&siteId=1