我碰到這個問題來解決,同時對Hackerrank挑戰整數數組中唯一的非對元素。XOR操作返回
/*
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操作如何能夠返回數組中的「孤獨整數」。我知道異或的兩個屬性,如:
1. a^a=0
2. a^0=a
但除此之外,我無法弄清楚XOR如何在這裏工作。
有another question上,以便具有相同的內容,但提出了一個不同的問題,所以我必須(再)問這個。
我高度讚賞如果有人可以提供此XOR操作的詳細說明。