#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
int n,result=0;
scanf("%d",&n);
if(n%2 == 0)
{
printf("impossible!\n"); //这样的序列的个数一定是奇数个元素
return 0;
}
int *a = new int[n];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
result ^= a[i];
}
printf("%d\n", result);
delete[] a;
return 1;
}
1,异或操作^是很特殊的。自己和自己异或,结果会得到全0;和全0异或,结果不变;和全1异或,结果会得到自己的取反。
2,利用这个特点。将序列的所有元素异或起来。成对的元素会异或得到0,单个的那个元素就会保留着。
该题目同时也是Leetcode上的一道最简单的题目。
class Solution {
public:
int singleNumber(int A[], int n) {
int i;
int result = 0;
for(int i=0;i<n;i++)
{
result ^= A[i];
}
return result;
}
};

本文介绍了一种使用异或运算找出数组中唯一单例元素的方法。通过异或所有数组元素,成对出现的元素相互抵消为0,最终剩下未配对的单例元素。这种方法适用于奇数长度的数组,并提供了C++代码实现。
16万+

被折叠的 条评论
为什么被折叠?



