只出现一次的数
作者:
hayate
,
2024-02-13 11:20:52
,
所有人可见
,
阅读 45
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1010; // 定义数组的最大长度
int a[N]; // 定义一个数组用于存储输入的整数
int n; // 定义一个整数变量n用于存储输入的整数的数量
int main()
{
cin >> n; // 从标准输入读取整数的数量
// 读取n个整数并存储到数组a中
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
// 初始化异或总和为0
int sum = 0;
// 遍历数组a中的每个元素,并将它们逐个进行异或操作
for(int i = 0; i < n; i++)
{
//因为满足交换律与结合律,所以
//在这个程序中,sum 初始值为0。遍历数组 a,并对每个元素执行异或操作。
//这样做的效果是,数组中出现两次的数字会被抵消(因为任何数与自己异或的结果是0),
//最终 sum 的值为数组中所有元素异或的结果。
sum = sum ^ a[i];
}
// 输出异或总和
cout << sum << endl;
return 0;
}