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

思路分析:

通过to_string将int类型转换为string类型然后遍历字符串。

代码:

模拟一

#include <iostream>
#include <string>

using namespace std;

int main(){
    
    
    string s;
    int count = 0, a, b;
    cin >> a >> b;
    for(int i = a; i <= b; i++) s = s + to_string(i);
    for(int i = 0; i < s.length(); i++){
    
    
        if(s[i] == '2'){
    
    
            count++;
        }
    }
    cout << count << endl;
    return 0;
}

AcWing题解
题目链接

猜你喜欢

转载自blog.csdn.net/zy440458/article/details/113793982
今日推荐