The number of specified digits#1609

The number of specified digits (Editorial)

Algorithm Analysis

Iterate through the digits of the number . Find the number of digits in the number . If the number is negative, then change its sign to the opposite.

Algorithm Implementation

Read the input data. If the number is negative, then calculate its absolute value.

scanf("%d %d", &n, &a);
if (n < 0) n = -n;

In the variable , count the number of digits .

res = 0;

Iterate through the digits of the number .

while (n > 0)
{
    if (n % 10 == a) res++;
    n /= 10;
}

Output the answer.

printf("%d\n", res);

Java Implementation

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner con = new Scanner(System.in);
        int n = con.nextInt();
        int a = con.nextInt();
        if (n < 0) n = -n;
        int res = 0;
        while (n > 0)
        {
            if (n % 10 == a) res++;
            n /= 10;
        }
        System.out.println(res);  
        con.close();
    }
}

Python Implementation

n = int(input())
a = int(input())
if n < 0: n = -n

res = 0
while n > 0:
    if n % 10 == a:
        res += 1
    n = n // 10

print(res)