您的位置:首页 > 其它

杭电——find your present (2)

2017-09-11 19:08 323 查看

question

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

use scanf to avoid Time Limit Exceeded

本题用位异或运算,运用数组会超时,下面为位异或知识点

位运算中的异或运算

按位异或运算定义,

0^0=0,0^1=1 0异或任何数=任何数

1^0=1,1^1=0 1异或任何数-任何数取反

异或,就是“看看你们到底一样不一样。不一样就为1,一样就为0。”

按位异或运算的规律是

定理一a ^ b = b ^ a

定理二 a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

定理三 a ^ b ^ a = b, a ^ a^ b = b, b ^ a^ a = b

定理四若d = a ^ b ^ c,则a = d ^ b ^ c

证明:

在d = a ^ b ^ c两边同时异或^ b ^ c,得

d ^ b ^ c =a ^ b ^ c ^ b ^ c

d ^ b ^ c =a ^ b ^ b ^ c ^ c,由定理三得

d ^ b ^ c =a ^ c ^ c,同样由定理三得

d ^ b ^ c =a

*特点:数a两次异或同一个数b(a=a^b^b)仍然为原值a.

异或的几个常见用途:

(1) 实现两个值的交换,而不必使用临时变量。

例如交换两个整数a=10100001,b=00000110的值,可通过下列语句实现:

    a = a^b;  //a=10100111

    b = b^a;  //b=10100001

    a = a^b;  //a=00000110

(2) 在汇编语言中经常用于将变量置零:

xor a,a

(3) 使某些特定的位翻转

例如对数10100001的第2位和第3位翻转,则可以将该数与00000110进行按位异或运算。

      10100001^00000110 = 10100111

(4)使用定理三进行编码解码

由B ^ A^ A = B,我们可以假设一聊天记录是B,密钥是A。现在B ^ A之后,成了密文了。为了解密,对密文再使用密钥A进行一次异或运算即可。也即是B ^ A^ A = B。

代码

#include<stdio.h>
int main()
{
<
938d
span class="hljs-keyword">int n,m,i,s;
while(scanf("%d",&n)&&n!=0)
{
s=0;
for(i=0;i<n;i++)
{
scanf("%d",&m);
s ^=m;
}
printf("%d\n",s);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: