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 integerN , 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
OutputS , the number that occurs only once.
Sample Input:1
In the first input, we see only one element (1) and that element is the answer.
In the second input, we see three elements; 1 occurs at two places and 2 only once. Thus, the answer is 2.
In the third input, we see five elements. 1 and 0 occur twice. The element that occurs only once is 2.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int N = key.nextInt();
int[] A = new int [N];
for(int n = 0; n < N; n++){
A[n] = key.nextInt();
}
boolean exist;
for(int i = 0; i < N; i++){
exist = false;
for(int n = 0; n < N; n++){
if(A[i] == A[n] && n != i){
exist = true;
}
}
if(!exist){
System.out.println(A[i]);
break;
}
}
}
}
Input Format
The first line of the input contains an integer
Constraints
Output Format
Output
Sample Input:1
1
1
Sample Output:11
Sample Input:23
1 1 2
Sample Output:22
Sample Input:35
0 0 1 2 1
Sample Output:32
ExplanationIn the first input, we see only one element (1) and that element is the answer.
In the second input, we see three elements; 1 occurs at two places and 2 only once. Thus, the answer is 2.
In the third input, we see five elements. 1 and 0 occur twice. The element that occurs only once is 2.
Bit Manipulation Challenges - Hacker Rank Solution
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int N = key.nextInt();
int[] A = new int [N];
for(int n = 0; n < N; n++){
A[n] = key.nextInt();
}
boolean exist;
for(int i = 0; i < N; i++){
exist = false;
for(int n = 0; n < N; n++){
if(A[i] == A[n] && n != i){
exist = true;
}
}
if(!exist){
System.out.println(A[i]);
break;
}
}
}
}
No comments:
Post a Comment