题目:
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?
思路:
由于相同值异或结果为0,0和非零数异或结果为数本身。
序列:2 3 3 7 4 4 5 5 7
2^3 = 1
1^3 = 2
2^7 = 5
5^4 = 1
1^4 = 5
5^5=0
0^5=5
5^7=2
class Solution {
public:
int singleNumber(int A[], int n) {
int result = 0;
for(int i = 0;i < n;++i){
result ^= A[i];
}
return result;
}
};