NOIP2013 计数问题 - 数字出现次数统计

问题描述:

试计算在区间 1 到 n 的所有整数中,数字 x (0≤x≤9) 共出现了多少次?例如,在 1 到 11 中,即在 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 中,数字 1 出现了 4 次。

输入描述:

2 个整数 n, x,之间用一个空格隔开。

输出描述:

1 个整数,表示 x 出现的次数。

用例输入 1:

11 1

用例输出 1:

4

用例输入 2:

2 1

用例输出 2:

1

提示:

对于 100% 的数据,1≤n≤1,000,000, 0≤x≤9。

C++ 代码示例:

#include <iostream>
#include <string>

using namespace std;

int countOccurrences(int n, int x) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        string numStr = to_string(i);
        for (char c : numStr) {
            if (c - '0' == x) {
                count++;
            }
        }
    }
    return count;
}

int main() {
    int n, x;
    cin >> n >> x;
    int result = countOccurrences(n, x);
    cout << result << endl;
    return 0;
}
NOIP2013 计数问题 - 数字出现次数统计

原文地址: https://www.cveoy.top/t/topic/cFhO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录