java - Counting a digit from second input
问题描述
If the user enter a first number (ex. 2) and then enter a second number (ex. 124218) then the the code will print how many two's are there in the second input.
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int num2 = in.nextInt();
int ans = 0;
while(num2 > 0){
int digit = num2 % 10;
if(digit == num){
ans++;
}
num2 /= 10;
}
System.out.println(ans);
but still doesn't count.
Input: 2 124218 Expected output: 2
EDIT: Nevermind i got it. just need to add some variable.
解决方案
您需要将提醒操作与除法分开,因为在提醒中您正在获取数字的最后一位并通过num
输入检查它,因此您需要在其他变量中执行此操作:
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int num2 = in.nextInt();
int last_digit = 0;
while (num2 > 0) {
last_digit = num2 % 10;
if (last_digit == num) {
num++;
}
num2 /= 10;
}
System.out.println(num);
推荐阅读
- spring-integration - 对 HttpOutboundGateway 进行轮询
- c++ - 多重声明与未定义
- javascript - 无法让预先编写的 Tizen 应用程序工作
- python - tree.put(key, value) 插入
- c# - 使用事件而不是抽象方法有什么好处?C#
- java - 将数组中的字符串与输入字符串进行比较?
- python - 如何使用 selenium python 注销linkedin
- android - 如何从工具栏中隐藏\显示 SearchView?
- maven - 添加 DevTools 依赖项会导致在 STS 中运行 Spring Boot 应用程序时出错
- service-worker - 在使用 Workbox 预缓存资产时跟踪进度