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?
Another same kind of problem with Single Number 2, I used the old method to solve it(sort and then search), but the method below is so perfect.
xor, ^.
this bit calculate will lead two same numbers to 0, and 0 xor any number is the original one...
so, right! Xor all the number, the same number(2 number) will xor to 0, and the left one is the single...
class Solution {
public:
int singleNumber(int A[], int n) {
int num, i;
for(i = num = 0; i < n; num^=A[i++]) ;
return num;
}
};