2015-03-31 52 views
0

我碰到這個問題來解決,同時對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操作的詳細說明。

回答

1

由於a^a對於任何a等於0,所有匹配的整數對將相互抵消,而留下0.然後與最終數字進行異或運算。由於0^a等於a任何a,則結果將是最終數目。 簡單的演示:

$ ruby -e 'puts [1,1,2,2,3,3,4,5,5,6,6].reduce :^' 
4 

你可以看到爲什麼這個作品,如果你去通過個人對:

1^1 = 0 
0^2 = 2 
2^2 = 0 
0^3 = 3 
3^3 = 0 
0^4 = 4 
4^5 = 1 
1^5 = 4 
4^6 = 2 
2^6 = 4 

0之間的切換結果和最新的數字,直到你得到的不合羣;之後,它會在這個數字和......之間切換,當你用最新的新號碼對它進行異或時,你會得到什麼。那裏的實際值並不重要,因爲當您在該數字的第二個副本中進行異或時,它將被刪除,並且您又回到了單例的副本。

我排序的數字,這樣才容易被發現的單,但由於異或撤銷本身的順序並不在所有問題:

$ ruby -e 'puts [6,3,4,1,1,2,2,6,3,5,5].reduce :^' 
4 

6^3是......一些號碼,那麼這個數字^ 4一些其他的號碼,然後你XOR與1,並沒有任何的事項,因爲那時你撤消1,然後與2另一中間結果扔,並撤消它了,然後你撤消6和3,讓你回到剛纔的4,你XOR 5再弄短暫的數量,然後由最後5沖走,留下,再一次,4