Advertisement
Shekhar777

Java Loops and Introduction to Arrays - Post Class - Mohit and array

Oct 19th, 2020
702
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. Q18-Mohit has an array of N integers containing all elements from 1 to N, somehow he lost one element from the array.
  2. Given N-1 elements your task is to find the missing one.
  3. Ans-import java.io.*; // for handling input/output
  4. import java.util.*; // contains Collections framework
  5.  
  6. // don't change the name of this class
  7. // you can add inner classes if needed
  8. class Main {
  9.     public static void main (String[] args){
  10.                       // Your code here
  11.         Scanner s=new Scanner(System.in);
  12.             int N=s.nextInt();
  13.             int arr[]=new int[N];
  14.             for(int i=0;i<N-1;i++){
  15.                 arr[i]=s.nextInt();
  16.             }
  17.             Arrays.sort(arr);
  18.             int sumOfAll = (N*(N+1))/2;
  19.       int sumOfArray = 0;
  20.       for(int j=0; j<=N-1; j++) {
  21.          sumOfArray = sumOfArray+arr[j];
  22.       }
  23.       int missingNumber = sumOfAll-sumOfArray;
  24.       System.out.println(missingNumber);
  25.    }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement