【算法分析1】
枚举[L,R]区间的所有整数,对于每个整数x:
先判断x的最后一位是否为2(即 x%10==2),然后将x的最后一位删除(即 x/=10),循环操作,直到x值为0。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int l,r,ans=0;
cin>>l>>r; //读入区间
for (int i=l; i<=r; ++i)//从left扫描到right,
{
int x=i; //对每一个i都判断其是否含有数字2
while (x>0) //只要x>0就需要进行拆分
{
if (x%10==2) ++ans;
x/=10;
}
}
cout<<ans;
return 0;
}
【参考程序2】
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char s[100]; //定义一个字符数组
int main()
{
int l,r,ans=0;
cin>>l>>r; //读入区间值L、R
for (int i=l; i<=r; ++i) // 扫描区间内每一个数
{
sprintf(s,"%d",i); //此语句实现将每一个数都转化为数字字符串
len=strlen(s);
for (int j=0; j<=len-1; ++j)//逐个检验每一个字符是否为'2'
if (s[j]=='2') ++ans;
}
cout<<ans;
return 0;
}