Here we need to get the following results
Sample Input : 1 3 4 5 6 7 8 9
Output : Missing number is 2
Sample Input : 1 2 3 4 5 7 8 9 10
Output : Missing number is 6
Output : Missing number is 2
Sample Input : 1 2 3 4 5 7 8 9 10
Output : Missing number is 6
Program:
/**
* @author Gaurav
*
*/
public class MissingNumberPuzzle {
* @author Gaurav
*
*/
public class MissingNumberPuzzle {
/* main method */
public static void main(String args[]) {
int array[] = { 1, 2,3, 4, 5, 6 };
System.out.println("Missing number is " + getMissingNumber(array));
}
public static void main(String args[]) {
int array[] = { 1, 2,3, 4, 5, 6 };
System.out.println("Missing number is " + getMissingNumber(array));
}
// Business logic to find missing number
static int getMissingNumber(int a[]) {
int temp = a.length;
for (int index = 0; index < temp; index++)
if (a[index] != (index + 1))
return (index + 1);
static int getMissingNumber(int a[]) {
int temp = a.length;
for (int index = 0; index < temp; index++)
if (a[index] != (index + 1))
return (index + 1);
// If all numbers from 1 to n
// are present
return temp + 1;
}
}
// are present
return temp + 1;
}
}
Can be done faster with binsearch
ReplyDelete