Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to find the missing number in a given Array from number 1 to n in Java?
If a single number is missing in an integer array that contains a sequence of numbers values, you can find it basing of the sum of numbers or, basing on the xor of the numbers.
Based on the sum of the numbers −
- The sum of n sequential numbers will be [n*(n+1)]/2. Using this get the sum of the numbers the n numbers.
- Add all the elements in the array.
- Subtract the sum of the numbers in the array from the sum of the n numbers.
Example
import java.util.Scanner;
public class MissingNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the n value: ");
int n = sc.nextInt();
int inpuArray[] = new int[n];
System.out.println("Enter (n-1) numbers: ");
for(int i=0; iOutput
Enter the n value:
5
Enter (n-1) numbers:
1
2
4
5
Missing number is: 3
Using XOR operation − Another way to find the missing number is using XOR.
- Find the XOR of all the numbers up ton.
- Find the XOR of all the numbers in the array.
- Then find the XOR of both results.
Example
import java.util.Scanner;
public class MissingNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the n value: ");
int n = sc.nextInt();
int inpuArray[] = new int[n];
System.out.println("Enter (n-1) numbers: ");
for(int i=0; iOutput
Enter the n value:
5
Enter (n-1) numbers:
1
2
4
5
Missing number is: 3
Advertisements
