Write a program to find Duplicate Number in Java

Here we are adding 1 to 30 numbers in the List and one of the series number 29 is repeated. We need to find out that repeated or duplicate number.

Code :
 import java.util.ArrayList;  
 import java.util.List;  
 public class FindDuplicateNum {  
      public static void main(String args[])  
      {  
           List<Integer> numbers=new ArrayList<Integer>();  
           for(int i=1;i<=30;i++)  
                {  
                numbers.add(i);  
                }  
           numbers.add(29);  
           System.out.println("Duplicate Number is:"+ duplicateNum(numbers));  
      }  
      public static int sum(List<Integer> numbers)  
      { int sum=0;  
           for(int num:numbers)  
           {  
                sum+=num;  
           }  
           return sum;  
      }  
      public static int duplicateNum(List<Integer> numbers)  
      {    
           int n=numbers.size()-1;  
           int total=n*(n+1)/2;  
           int sum=sum(numbers);  
           return sum-total;  
      }  
 }  

Output:
Duplicate Number is:29

No comments: