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;
An operator is used to manipulate individual data items and return a result. These items are called operands or arguments.
Some of the types are: Arithmetic Operators. Unary Operators. Assignment Operator. Relational Operators.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With