提
前言
第一题
第二题
一、思路分析
1.对于第一题思路较为简单,对于每一位我们可以通过右移 并与1 进行与(&)运算 获取每一位的数字,如果是1 对于ans 就++ ,如果是零就不用改动。
2.对于第二题来说,需要我们知道异或运算具有结合律和交换律,我们可以列出(a1 ^ x) ^ (a2 ^ x) ^ (a3 ^ x) = (a1 ^ a2 ^ a3 ^ x ^ x ^ x) 而我们知道对于 x ^ x 进行运算一定为 0 ,并且 0 ^ x = x ,最后我们就可以推导出这样一个等式: a1 ^ a2 ^ a3 = x; 那么因为题目给出了 x 是奇数个 所以我们最后都可以化简成为这样的形式,x就是我们所要求的答案。
二、代码实例
First
代码如下:
#include<bits/stdc++.h>
using namespace std;
using ll = long long ;
const int N = 2e5 + 10;
int n;
int a[N];
int f(int x)
{
int num = 0;
while(x)
{
if(x & 1) num ++;
x >>= 1;
}
return num;
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 0; i < n; i ++)
{
cin >> a[i];
cout << f(a[i]) << ' ';
}
cout << '\n';
return 0;
}
Second
代码如下(示例):
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int t;
const int N = 1010;
int a[N];
int main()
{
cin >> t;
while(t --)
{
int n;
cin >> n;
int res = 0;
for(int i = 0; i < n; i ++)
{
cin >> a[i];
res ^= a[i];
}
cout << res << '\n';
}
return 0;
}