top1编程
← 返回题目
题解

【入门】记数问题

1 条题解

  • 0
    @ 2026-7-29 0:18:50
    #include <iostream>
    using namespace std;
    
    int main() {
        int n, x;
        cin >> n >> x;
        
        int count = 0; // 统计x出现的总次数
        
        // 遍历1到n的所有数
        for (int num = 1; num <= n; ++num) {
            int temp = num; // 临时变量,避免修改原数
            // 逐位拆分temp的每一位
            while (temp > 0) {
                int digit = temp % 10; // 获取最后一位
                if (digit == x) {
                    count++;
                }
                temp = temp / 10; // 去掉最后一位
            }
        }
        
        cout << count << endl;
        return 0;
    }
    
    • 1