I recently came across this question on Leetcode and figured out a solution that I need some clarification with:
Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for(auto & c : nums) {
result ^= c;
}
return result;
}
};
First of all, what sorts of keywords should I be paying attention to in order to figure out that I should be using an XOR operation for this question?
Also, why does XOR'ing all items in the vector with each other give us the one that is not repeated?
Thank you all for these responses, here is some more information on bitwise properties for anyone else interested: More bitwise info
question from:https://stackoverflow.com/questions/41963898/xor-operation-intuition