(UVA) Lonely Integer - Solution
Link to the problem: https://www.hackerrank.com/challenges/lonely-integer
The solution below used Bit Manipulation to solve this problem.
If we do "a xor a", it result in 0. Once each number would appear twice, except for one of them, we can use this strategy.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static int lonelyInteger(int[] a) {
int result = 0;
for (int i = 0; i < a.length; i++) {
result ^= a[i];
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
System.out.println(lonelyInteger(a));
}
}
The solution below used Bit Manipulation to solve this problem.
If we do "a xor a", it result in 0. Once each number would appear twice, except for one of them, we can use this strategy.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static int lonelyInteger(int[] a) {
int result = 0;
for (int i = 0; i < a.length; i++) {
result ^= a[i];
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
System.out.println(lonelyInteger(a));
}
}
Comments
Post a Comment