We will see how to find missing number in an given array.
Answer is very simple just to remember/recollect our mathematics which we studied in earlier days.
If we know how to find sum of n numbers, answer is simple.
1. First we need to calculate the sum of n numbers. Here n is length of given array + 1, because 0ne number is missed in given array.
we can calculate the sum of n numbers using n*(n+1)/2.
2. Second we need to calculate the sum of all numbers of an array.
Finally we can find missing number in an array as follows:
package com.sample.java.testing;
public class FindMissNumber {
public static void main(String a[]){
int a1[] = {1,3,4,2,6,7,8,9};
int total = (a1.length+1)*(a1.length+2)/2; ////here n is nothing but arraylength+1
System.out.println(total);
int total1 = 0;
for (int i : a1) {
total1 = total1 + i;//total of given numbers in an array
}
System.out.println("missing number is" + (total - total1));
}
}
Answer is very simple just to remember/recollect our mathematics which we studied in earlier days.
If we know how to find sum of n numbers, answer is simple.
1. First we need to calculate the sum of n numbers. Here n is length of given array + 1, because 0ne number is missed in given array.
we can calculate the sum of n numbers using n*(n+1)/2.
2. Second we need to calculate the sum of all numbers of an array.
Finally we can find missing number in an array as follows:
package com.sample.java.testing;
public class FindMissNumber {
public static void main(String a[]){
int a1[] = {1,3,4,2,6,7,8,9};
int total = (a1.length+1)*(a1.length+2)/2; ////here n is nothing but arraylength+1
System.out.println(total);
int total1 = 0;
for (int i : a1) {
total1 = total1 + i;//total of given numbers in an array
}
System.out.println("missing number is" + (total - total1));
}
}
No comments:
Post a Comment