题目来自:http://218.5.5.242:9018/JudgeOnline/problem.php?id=1303
题目讲解:
这道题非常简单,不用一位一位算,直接套用cstring库中的sprintf函数,将数字转换为字符数组,使用方法如下:
sprintf(数组名称,"数字类型",字符数组大小);
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int main(){ int a,b,ans = 0; cin >> a >> b; for (int i = a;i <= b;i++){ char buf[256]; memset(buf,'\0',256); sprintf(buf,"%d",i); for (int j = 0;j < strlen(buf);j++){ if (buf[j] == '2'){ ans++; } } } cout << ans; return 0; }