AcWing 441 digital statistics

Title description:

Please count the number of occurrences of the number 2 among all integers in a given range [L, R]. 

For example, given the range [2, 22], the number 2 appears once in the number 2, once in the number 12, once in the number 20, once in the number 21, and appears in the number 22 2 times, so the number 2 appears 6 times in this range.

Input format

The input is 1 line, two positive integers L and R, separated by a space.

Output format

The output has a total of 1 line, indicating the number of occurrences of the number 2.

data range

1≤L≤R≤10000

Input sample:

2 22

Sample output:

6
#include <iostream>
#include <cstdio>

using namespace std;

int L, R;

int CouTwo(int x)
{
    int cnt = 0;
    while(x)
    {
        if(x % 10 == 2)
            cnt++;
        x /= 10;
    }
    return cnt;
}

int main()
{
    scanf("%d%d", &L, &R);

    int sum = 0;
    for(int i = L; i <= R; i++)
    {
        sum += CouTwo(i);
    }

    printf("%d\n", sum);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/113861400