查找丢失号码的Java程序
鲍勃还是个小孩子,刚刚学会了数数。他坐在他的房子里,开始玩他的玩具数量。他的左边有n个玩具号码,右手有n个玩具的数量。突然他的母亲叫他,他把所有的数字混合起来就走了。当他回来时,他意识到他忘记了他所拥有的数字的计数。给定所有玩具数字,帮助他找到数组中存在的n值或打印 -1。
例子
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.
方法
解决方案非常简单。我们可以只接受字符串中的输入并计算空格的数量,这将是数组的实际长度。
算法
- 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.
它是如何工作的?
- 当我们将输入作为字符串时,字符串中存在的元素数等于存在的空格数 +1。
- 元素的实际数量等于字符串-1 中存在的元素数量。
Required answer = number of spaces +1 -1 = number of spaces
我执行:
Java
// Java program to find the lost count
import java.util.*;
public class GFG {
// find lost count
public static void findLostCount(String s)
{
// counting the number of elements using the split
// function -1
int count = s.split(" ").length - 1;
// if the value count is present then print count
// else print -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);
// Taking input as string
String s = "5 7 4 3 2 6";
findLostCount(s);
}
}
输出
Number of elements 5