Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "^= "operator in Java?

I was studying on leetcode for an interview. There were a question about finding missing number unpaired in array. I solved it by using HashSet. But i saw the below solution which is more efficient than mine.My question is that what the logic XOR of a ^= nums[i] means ?

int a = 0;
for (int i = 0; i < nums.length; i++) {
    a ^= nums[i];
}
return a;
like image 586
Trinity Avatar asked Oct 17 '19 12:10

Trinity


People also ask

What is the purpose of operator?

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments.

What is operator and its types in Java?

Some of the types are: Arithmetic Operators. Unary Operators. Assignment Operator. Relational Operators.


1 Answers

You are now familiar by all answers that ^= is the XOR-and-becomes operator.

As x ^ x == 0 and x ^ 0 == x doing a cumulative XOR will remove twice occurring duplicates and the result will be the sole single occurrence.

3 ^ 5 ^ 3 ^ 7 ^ 5 = (3 ^ 3) ^ (5 ^ 5) ^ 7 = 0 ^ 0 ^ 7 = 7
3   6   5   2   7  <--- stepwise accumulated: 3=1+2, 5=1+4, 7=1+2+4

XOR is an interesting commutative and associative function "bit is different" as it does not loose information,

z = x ^ y   =>   y = z ^ x
like image 154
Joop Eggen Avatar answered Sep 28 '22 07:09

Joop Eggen