Missing Number in Array


public class MissedNumberTest {

public static void main(String[] args) {
// This program find out only one number in sequence orde
//1) Calculate the sum of all numbers stored in the array .
//2) Subtract the sum from (n+1)*(n+2)/2
int arr[]={1,2,4,5};
int sum = 0;
int n=arr.length;
//int emptySlotIndex = -1;

for (int i = 0; i < arr.length; i++)
{
  /*if (arr[i] == 0)
    emptySlotIndex = i;*/
  sum += arr[i];
}
int sub=(n+1)*(n+2)/2; // n*(n+1)/2 this scenario n=arr.length+1

System.out.println(sub-sum);

}

}

Comments