【发布时间】:2015-03-31 01:28:47
【问题描述】:
我在解决 Hackerrank 挑战时遇到了这个问题。
/*
Problem Statement
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
Input Format
The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.
Constraints
1≤N<100
N % 2=1 (N is an odd number)
0≤A[i]≤100,∀i∈[1,N]
Output Format
Output S, the number that occurs only once.
*/
我在这种情况下编写的常规解决方案非常复杂,有很多嵌套的 if 循环。经过一番搜索,我发现这个解决方案通过简单地将整数数组中的所有元素相互异或来解决问题,结果是孤独的整数。
这是相关的方法(main() 方法,它接受输入并将其解析为整数数组,未显示,因为它在这里不相关):
static int lonelyinteger(int[] a) {
int n = a.length;
int result = 0;
for( int i = 0; i < n; i++) {
result = result ^ a[i];
}
return result;
}
我不确定这个 XOR 操作如何能够返回数组中的“孤独整数”。我知道 XOR 的两个属性,如:
1. a^a=0
2. a^0=a
但除此之外,我不太明白 XOR 是如何在这里工作的。
在 SO 上有 another question 具有相同的内容,但这提出了一个不同的问题,所以我不得不问这个(再次)。
如果有人能提供此 XOR 操作的详细解释,我将不胜感激。
【问题讨论】: