AcWing 441数字统计

题目描述:

请统计某个给定范围[L, R]的所有整数中,数字 2 出现的次数。 

比如给定范围[2, 22],数字 2 在数 2 中出现了 1 次,在数 12 中出现 1 次,在数 20 中出现 1 次,在数 21 中出现 1 次,在数 22 中出现 2 次,所以数字 2 在该范围内一共出现了 6 次。

输入格式

输入共 1 行,为两个正整数 L 和 R,之间用一个空格隔开。

输出格式

输出共 1 行,表示数字 2 出现的次数。

数据范围

1≤L≤R≤10000

输入样例:

2 22

输出样例:

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44620183/article/details/113861400