Problem Description
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
翻译
问题描述
在新年晚会上,每个人都会得到一份“特别礼物”。现在轮到你准备特别礼物了,很多礼物都放在桌上,只有一件是你的。每件礼物上都有一个卡号,而你的礼物的卡号将是与其他所有礼物不同的卡号,你可以假设只有一个号码。出现奇数次。例如,有5个存在,他们的卡号是1,2,3,2,1。所以你的存在将是一个卡号为3,因为3是不同于所有其他的数字。
输入
输入文件将由几个案例组成。
每种情况将首先由一个整数n(1<=n<1000000,n是奇数)表示。然后,在一行中给出n个正整数,所有整数都小于2^31。这些数字表示礼物的卡号。n=0结束输入。
产量
对于每种情况,在一行中输出一个整数,这是您当前的卡号。
分析
初看问题想用枚举,计数排序,统计所有数字出现的次数,然后输出奇数次的那个数。但好像计算的复杂度太大。后面参考了一个c语言的神奇方法 用到了异或运算符
利用异或运算。
符号是^.
异或是个位运算符号,具体是怎么操作的请百度,这里有个特性使得他能产生一种巧方法
a^a=0
0^c=c
没错,例如样例
5
1 1 3 2 2
如果我们用异或运算计算就是
11322
由于1^1=0 2^2=0,那么就只剩下了唯一的一个3了。
如果有3个3,那么前面偶数个3由于3^3=0,势必也会只留下一个孤单的3.
那么答案就只能是那个多余的数字了。
源代码
#include<stdio.h>
int main()
{
int t;
while(scanf("%d",&t)&&t!=0)
{
int sum;
scanf("%d",&sum);
t--;
while(t--)
{
int a;
scanf("%d",&a);
sum^=a;
}
printf("%d\n",sum);
}
return 0;
}