Java Program to Find the Lost Number
Last Updated :
04 Jan, 2021
Bob is a small kid and just learned to count numbers. He sat in his house and started playing with his number of toys. He was having some n toy numbers on his left and the count of those n toys in the right hand. Suddenly his mother called him, and he mixed all the numbers and left. When he returned he realized that he forgot the count of the numbers he was having. Given all the toy numbers help him find the value of n if present in the array or print -1.
Examples
Input: 5 7 4 3 2 6
Output: 5
Explanation: There are 6 toy numbers out of which one is the length hence we print 5.
Input: 10 14 11 15
Output: -1
Explanation: There are 4 toy numbers but we do not have 3 as the value in the array hence we print -1.
Approach
The solution is pretty simple. We can just take the input in a string and count the number of spaces, which will be the actual length of the array.
Algorithm
- Take the input as string.
- Count the number of spaces present in the string.
- If the number of spaces present is equal to any of the element present in the array then print that number else print -1.
- To find the element is present or not, we use string.indexOf() method.
How does it work?
- When we take the input as a string the number of elements present in the string is equal to the number of spaces present +1.
- The actual number of elements is equal to the number of elements present in the string -1.
Required answer = number of spaces +1 -1 = number of spaces
Implementation:
Java
import java.util.*;
public class GFG {
public static void findLostCount(String s)
{
int count = s.split( " " ).length - 1 ;
if (s.indexOf(Integer.toString(count)) != - 1 )
System.out.println( "Number of elements "
+ count);
else
System.out.println(- 1 );
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s = "5 7 4 3 2 6" ;
findLostCount(s);
}
}
|
Output
Number of elements 5
Share your thoughts in the comments
Please Login to comment...