您的位置:首页 > 其它

OJ, VJfind your present (2)——用异或运算找到一列数中(该列数必然只含奇数个数)唯一出现奇数次数的数是谁

2020-07-11 20:44 99 查看

In the new year party, everybody will get a “special present”.Now it’s your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and your present’s card number will be the one that different from all the others, and you can assume that only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card number of 3, because 3 is the number that different from all the others.
Input
The input file will consist of several cases.
Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input.
Output
For each case, output an integer in a line, which is the card number of your present.
Sample Input
5
1 1 3 2 2
3
1 2 1
0
Sample Output
3
2

对题目中所指明的“···数”一定要注意。

题目数据大,一般的算法容易超时。

这里介绍位异或运算的概念:

1.进行异或计算前会把数值都转换为二进制:
5和3转为二进制分别为:0101 、0011
0101
xor
0011

结果
0110
2.再把结果 0110 转换为十进制的:6

按位异或的3个特点:
(1) 00=0,01=1 0异或任何数=任何数
(2) 10=1,11=0 1异或任何数-任何数取反
(3) 任何数异或自己=把自己置0

位异或运算性质:
(1)位异或运算满足加法交换律。

解题得用位异或的4个特点来解。

由题,找到唯一出现次数为奇数次的数。其它数都为出现偶数次。由位异或运算特点和性质。若一个数出现次数为偶数次,那么经偶数次异或运算后为0。若一个数出现次数为奇数次,该数经前面偶数次异或运算后为0,0异或该数为该数。

再由异或运算满足加法交换律。

找到2n-1个数中唯一出现奇数次数的数,只需对该列数进行2n-1次异或运算即可。

代码:

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
long long  a, b, t, i, xor_result, n;
while(scanf("%lld", &t) != EOF)
{
xor_result = 0;
for(i = 0; i < t; i++)
{
scanf("%lld", &n);
xor_result ^= n;
}
printf("%lld\n", xor_result);
}
return 0;
}

以上代码参考博客:https://www.geek-share.com/detail/2717063991.html

感谢他的解析!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: