题目描述
Single Number
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?
解法
利用位异或操作:a&a=0; a&0=a,异或操作符合交换律和结合律(参见c/c++位操作简介--移位、位与、位或、异或)。
代码
class Solution {
public:
int singleNumber(int A[], int n) {
int res=A[0];
for(int i=1;i<n;++i)
res^=A[i];
return res;
}
};
参考
http://www.cnblogs.com/lailailai/p/3681697.html