Description
Thereis N pairs of balls in a small box. That means the number for eachpair is the same. However, for some reason, a ball is lost. Now, youwill get the number of the rest. Can you find the number of the lostball as fast as possible?
Input
Theinput consists of several test cases. For each case, the first linecontains an integer N(1<= N <= 500000), the total number oftoys in the field. Then a line follow, which contains 2*N-1 numbers,which will is positive and not exceed 2*10^9. The input is terminatedby N=0.
Output
Foreach test case, print in one line the number of the lost ball.
SampleInput
3
24 5 4 5
5
199342 199 341 332 340 332 342 340
0
SampleOutput
2
341
解题思路:因为对于如此多的输入数据(500000×2-1),进行全部存储是不可行的,部分存储也不现实,因为输入数据是随机顺序的。因此采用另一种思路,假设一种操作f,使得待求数xi = f(x1,x2,……xn)。加减乘除肯定不行,逻辑运算也不行,那么只剩下位运算,我们知道a^a(按位异或操作)=0,0^b=b,且按位异或满足交换律和结合律,那么,将所有输入数据按位进行异或操作,最后将得到待求数xi
package OJ;
import java.math.BigInteger;
import java.util.*;
public class P23_temp {
/**
* @param args
*/
public static BigInteger xor(BigInteger i, BigInteger j){
// return i^j;//按位异或
return i.xor(j);
}
public static void main(String[] args) {
BigInteger p,q;
ArrayList<BigInteger> results = new ArrayList<BigInteger>();
Scanner in = new Scanner(System.in);
while(true){
BigInteger n = in.nextBigInteger();
if(n.equals(BigInteger.ZERO))
break;
p = BigInteger.ZERO;
BigInteger num = n.multiply(new BigInteger("2")).subtract(new BigInteger("1"));
for(BigInteger i=BigInteger.ZERO;i.compareTo(num) == -1;i = i.add(BigInteger.ONE)){
q = in.nextBigInteger();
p= xor(p,q);
}
results.add(p);
}
for(BigInteger i : results){
System.out.println(i);
}
}
}