杭电——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
51 1 3 2 2
3
1 2 1
0
Sample Output
32
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); } }
相关文章推荐
- 杭电 2095 find your present (2)【位运算 异或】
- 杭电OJ(HDOJ)2095题:find your present (2)(数论)
- 杭电 acm find your present (2)
- 杭电oj find your present (2)
- 杭电2095(find your present (2))
- 武汉科技大学计算机学院菜鸟杯:find your present (2).(杭电2095)
- 杭电2095 find your present (2)
- 【杭电-oj】-2095-find your present (2)(输出奇数个的数)
- 【杭电ACM】1.2.5 find your present (2)
- 【菜鸟做水题】:杭电 find your present(用异或的解题思想)
- Find your present!(杭电1563)
- 杭电OJ-- 2095 find your present (依然很水)
- hdu - 2095 - find your present (2)(异或)
- hdoj-2095-find your present (2)【位异或】
- hdu2095 find your present (2)(C语言
- find your present (2) v【 异或运算的巧用】
- 零起点学算法82——find your present
- J - find your present (2)
- HDU 2095 find your present (2)
- hdu2095 find your present(2)