希望某天什么题我都能这么丝滑!记录一下

题目描述

链接:https://ac.nowcoder.com/acm/contest/19859/A 来源:牛客网

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

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

输入描述:

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

输出描述

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

#include <iostream>
#include <string>

class mySolution{
public:
    int howMany2(int lower,int upper){
        int count=0;
        for(int i=lower;i<=upper;i++){
            std::string aString=std::to_string(i);
            for(char ch:aString){
                if(ch=='2') count++;
            }
        }
        return count;
    }    
};

int main(){
    mySolution*solution=new mySolution();
    int lower,upper;
    while(std::cin>>lower>>upper){
        int answer=solution->howMany2(lower, upper);
        std::cout<<answer<<std::endl;
    }
    return 0;
}