首页 > 解决方案 > 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.

标签: javaloops

解决方案


您需要将提醒操作与除法分开,因为在提醒中您正在获取数字的最后一位并通过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);

推荐阅读