Java Program to find a missing number in a sequence

     Problem: You have a sequence of consecutive numbers; the list missed a number between the sequence. How will you find the missed number.

Solution:

Try these two methods.

1.Using XOR method

              This method uses the XOR logic.

  • It gets the array and last number in the number sequence.
  • Using two for loops, the array and last number is used the XOR logic to find the missing number.
  • Finally, it prints the missing number.

Program:

public class MissingNOXOREg {

    public static int findIt(int[] a, int n) {

        int xor1 = 0, xor2 = 0;

        for (int i = 1; i <= n; i++) {

            xor1 ^= i;

        }

        for (int num : a) {

            xor2 ^= num;

        }

       return xor1 ^ xor2;

    }

   public static void main(String[] args) {

        int[] a = {1, 2, 4, 5};

        int n = 9;

        System.out.println("Missing Number: " + findIt(a, n));

    }

}

Output:

C:\raji\blog>javac MissingNOXOREg.java

C:\raji\blog>java MissingNOXOREg

Missing Number: 3

2.Using Sum Formula

              This method uses the sum formula.

  • ·       The input is last number and array of elements.
  • ·       It finds the sum of n natural numbers and sum of the array elements.
  • ·       If you find the difference of these two numbers, it is the missing number.
  • ·       At last, print the missed number.

Program:

public class MissingNoEg {

    public static int findIt(int[] a, int n) {

        int e_Sum = n * (n + 1) / 2;

        int a_Sum = 0;

       for (int no: a) {

            a_Sum += no;

        }      

        return e_Sum - a_Sum;

    }

    public static void main(String[] args) {

        int[] a = {1, 3, 4, 5, 6};

        int n = 6;

        System.out.println("Missing Number in the sequence is :"+findIt(a,n));

    }

}

Output:

Compile and execute theprogram to get the output.

C:\raji\blog>javac MissingNOEg.java

C:\raji\blog>java MissingNoEG

Missing Number in the sequence is :2

These are the two methods to find the missing number in the sequence in java. Keep coding!!!

No comments:

Post a Comment