The logic is very simple here, see the below.
- At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number.
- Then , we need to calculate the sum of all those natural number.
- Then we will subtract each element from the given list from sumOfNaturalNumbers.
- Now, the at the last the value inside sumOfNaturalNumbers is the missing number.
FindOneMissingNumber.java
package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
/**
* This program finds the missing number from a list. This is only for one
* missing number using core java before jdk 8.
*
* @author manoj.bardhan
*
*/
public class FindOneMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(
Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));
int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));
for (int i = 0; i < numberList.size(); i++) {
/*
* Substract each elements from list from sumOfNaturalNumbers and
* the final value will be the missing.
*/
sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
}
int missingNumber = sumOfNaturalNumbers;
System.out.println("Missing Number is :: " + missingNumber);
}
// Find the sum of all natural numbers up to limitNumber.
private static int getSumUptoMax(int limitNumber) {
int sum = 0;
for (int i = 1; i <= limitNumber; i++) {
sum = sum + i;
}
return sum;
}
// Find the greatest value from the list
private static int findMax(ArrayList<Integer> numberList) {
int largest = 0;
for (int i = 0; i < numberList.size() - 1; i++) {
if (numberList.get(i) >= largest) {
largest = numberList.get(i);
}
}
return largest;
}
}
Output -
Missing Number is :: 12
Happy Learning.
Follow for more details on @Facebook!!!
Find More :-
Find More :-
- Java 8 use Option - avoid NullPointerException
- Producer & Consumer problem solution using BlockingQueue.
- Write your first groovy program.
- Top 10 groovy interview question.
- Difference between groovy and java.
- What is full stack development experience.
- 5 fundamental questions of groovy.
- Write your first java program.
- Reverse string using recursive method in java.
- Comparator Interface with Examples
- Find the smallest number in an array.
No comments:
Post a Comment