A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired.
Write a function:
function solution(A);
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000]; each element of array A is an integer within the range [1..1,000,000,000]; all but one of the values in A occur an even number of times.
Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
방법
xor을 이용 0과 어떤 수 n을 xor 연산하면 n이된다. 000 xor 101의 결과는 101이다. 어떤 수 n에 x를 짝수번 xor연산 할 경우 그 값은 n과 동일하다. 10진수 5은 2진수로 101이고 10진수 3은 2진수로 011이다. 101 xor 011의 결과는 110 이고 110 xor 011의 결과는 101이 된다. 즉 0에 짝수개 만큼 존재하는 수들을 xor연산하면 그 결과는 0이 되고 짝수개가 존재하는 수들 가운데 홀수개가 존재하는 수를 xor하면 결국 홀수개가 존재하는 수의 값이 남는다. 0에 7, 5, 7, 4, 5를 xor연산하면 7과 5는 두 개씩 존재하기 때문에 0이되고 하나만 존재하는 4의 값만 남는다.
코드
1 2 3 4 5 6 7 8 9
functionsolution(A) { // write your code in JavaScript (Node.js 8.9.4) var result = 0; for(var i=0; i<A.length; i++){ result = result^A[i]; } return result; }