【题目来源】
https://www.luogu.com.cn/problem/P1179
【题目描述】
请统计某个给定范围 [L,R] 的所有整数中,数字 2 出现的次数。
比如给定范围 [2,22],数字 2, 在数 2 中出现 1 次,在数 12 中出现 1 次,在数 20 中出现 1 次,在数 21 中出现 1 次,在数 22 中出现 2 次,所以数字 2 在该范围内一共出现了 6 次。
【输入格式】
2个正整数 L 和 R,之间用一个空格隔开。
【输出格式】
数字 2 出现的次数。
【算法代码】
#include <iostream>
using namespace std;
int cnt;
int main() {
int x;
int L,R;
scanf("%d %d",&L,&R);
for(int i=L; i<=R; i++) {
x=i;
while(x!=0) {
if(x%10==2) cnt++;
x=x/10;
}
}
printf("%d",cnt);
return 0;
}
/*
in:2 22
out:6
in:2 100
out:20
*/