题目描述
给定一个大小为n的非负整数数组a。
你可以选定一个非负整数x,并令bi=ai⊕x,其中1≤i≤n,请问是否存在x,使得b1⊕b2⊕⋅⋅⋅⊕bn=0?
输入
第一行,一个整数t,表示有t(1≤t≤200)个案例,对于每个案例:
第一行:一个整数n(1≤n≤1000,且n为奇数),表示数组的大小。
第二行:n个整数,表示数组a(0≤ai≤10^9)。
输出
对于每个案例:
若存在这样的x,则输出x;否则,输出−1−1。
样例输入
2
3
2 5 2
3
4 5 0
样例输出
5
1
思路:看到这道题使用的是异或运算,首先应该明确异或运算的概念
并且有以下两条重要的定理:
恒等律:X ⊕ 0 = X
归零律:X ⊕ X = 0
当我们将题目中的式子展开来,就可以发现里面的公式可以化简到变成a1^a2^a3...^ai=x的形式,此时求出x即可
示例代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
int n;
cin>>t;
while(t--)
{
ll ans=0;
cin>>n;
for(int i=1;i<=n;i++)
{
ll x;
cin>>x;
ans ^= x;
}
cout<<ans<<'\n';
}
return 0;
}
通过: