Files

34 lines
895 B
Java
Raw Permalink Normal View History

2017-03-05 00:26:42 -06:00
// Author: Rodney Shaghoulian
2018-07-27 16:45:56 -07:00
// Github: github.com/RodneyShag
// HackerRank: hackerrank.com/RodneyShag
2017-03-05 00:26:42 -06:00
import java.util.Scanner;
2017-04-05 18:42:35 -05:00
// O(n) runtime. O(1) space. Uses XOR. Keep in mind:
// 1) x ^ x = 0
// 2) x ^ 0 = x
// 3) XOR is commutative and associative
2017-03-05 00:26:42 -06:00
public class Solution {
2017-09-11 09:32:17 -07:00
public static void main(String[] args) {
2017-04-05 18:42:35 -05:00
/* Save input */
2017-03-05 00:26:42 -06:00
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
2017-04-05 18:42:35 -05:00
int [] array = new int[n];
2017-03-05 00:26:42 -06:00
for(int i = 0; i < n; i++){
array[i] = scan.nextInt();
}
scan.close();
System.out.println(lonelyInteger(array));
}
/* XORs all numbers in array together */
public static int lonelyInteger(int [] array) {
int val = 0;
for (int num : array) {
val = val ^ num; // ^ is XOR operator
}
return val;
}
}