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
翻譯
問題描述
在新年晚會(huì)上,每個(gè)人都會(huì)得到一份“特別禮物”。現(xiàn)在輪到你準(zhǔn)備特別禮物了,很多禮物都放在桌上,只有一件是你的。每件禮物上都有一個(gè)卡號(hào),而你的禮物的卡號(hào)將是與其他所有禮物不同的卡號(hào),你可以假設(shè)只有一個(gè)號(hào)碼。出現(xiàn)奇數(shù)次。例如,有5個(gè)存在,他們的卡號(hào)是1,2,3,2,1。所以你的存在將是一個(gè)卡號(hào)為3,因?yàn)?是不同于所有其他的數(shù)字。
輸入
輸入文件將由幾個(gè)案例組成。
每種情況將首先由一個(gè)整數(shù)n(1<=n<1000000,n是奇數(shù))表示。然后,在一行中給出n個(gè)正整數(shù),所有整數(shù)都小于2^31。這些數(shù)字表示禮物的卡號(hào)。n=0結(jié)束輸入。
產(chǎn)量
對于每種情況,在一行中輸出一個(gè)整數(shù),這是您當(dāng)前的卡號(hào)。
分析
初看問題想用枚舉,計(jì)數(shù)排序,統(tǒng)計(jì)所有數(shù)字出現(xiàn)的次數(shù),然后輸出奇數(shù)次的那個(gè)數(shù)。但好像計(jì)算的復(fù)雜度太大。后面參考了一個(gè)c語言的神奇方法 用到了異或運(yùn)算符
利用異或運(yùn)算。
符號(hào)是^.
異或是個(gè)位運(yùn)算符號(hào),具體是怎么操作的請百度,這里有個(gè)特性使得他能產(chǎn)生一種巧方法
a^a=0
0^c=c
沒錯(cuò),例如樣例
5
1 1 3 2 2
如果我們用異或運(yùn)算計(jì)算就是
11322
由于1^1=0 2^2=0,那么就只剩下了唯一的一個(gè)3了。
如果有3個(gè)3,那么前面偶數(shù)個(gè)3由于3^3=0,勢必也會(huì)只留下一個(gè)孤單的3.
那么答案就只能是那個(gè)多余的數(shù)字了。
源代碼
#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;
}