OddOccurrencesInArray
Find value that occurs in odd number of elements.
Task Score
100%
Correctness
100%
Performance
100%
같은 수 끼리 xor 연산을 하면 0이 되고, 0과 숫자 n을 xor 연산하면 n이 된다는 것을 이용해서 풀면 쉽게 해결할 수 있다.
짝수인 수는 각각 xor 연산을 통해 0이 되고, 홀수인 수는 마지막 남은 숫자 하나가 0과 xor연산을 해 자기자신만 남게 된다. 그러므로 모든 연산을 마친 후 xor연산의 결과를 반환해주면 된다.
x
// you can also use imports, for example:// import java.util.*;// you can write to stdout for debugging purposes, e.g.// System.out.println("this is a debug message");class Solution { public int solution(int[] A) { int result = 0; for (int i = 0; i < A.length; i++) result = result ^ A[i]; return result; }}'공부 > algorithm' 카테고리의 다른 글
| [codility] PermMissingElem (2) | 2018.05.22 |
|---|---|
| [codility] FrogJmp (0) | 2018.05.22 |
| [codility] CyclicRotation (0) | 2018.05.22 |
| [codility] BinaryGap (0) | 2018.05.22 |
| [programmers] 숫자의 표현 (0) | 2018.05.22 |
댓글