标签:lintcode
Given 2*n + 1 numbers, every numbers occurs twice except one, find it.
Example
Given [1,2,2,1,3,4,3], return 4
http://www.lintcode.com/en/problem/single-number/
int singleNumber(vector<int> &A) {
// write your code here
if (A.size() == 0) {
return 0;
}
int ret = A[0];
for (int i = 1; i < A.size(); i++) {
ret = ret ^ A[i];
}
return ret;
}
异或运算具有如下性质:
1、性质
0 ^ 1 = 1
0 ^ 0 = 0
1 ^ 1 = 0
2、满足结合律:
a ^ b = b ^ a;
3、满足交互律:
a ^ ( b ^ c) = (a ^ b) ^ c;
因为异或运算满足结合律和交换律,并且相同元素的异或运算结果为0,所以当把所有元素抑或后,最后的结果就是那个不同元素
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:lintcode
原文地址:http://blog.csdn.net/richard_rufeng/article/details/46956889