题目
【问题描述】
在1至2019中,有多少个数的数位中包含数字9?
注意,有的数中的数位中包含多个9,这个数只算一次。例如,1999这个数包含数字9,在计算时只是算一个数。
【答案提交】
这是一道结果填空的题,你只需要算出结果后提交即可。本题的结果为一个整数,在提交答案时只填写这个整数,填写多余的内容将无法得分。
方法1:
#include <iostream>
#include <cstdio>//用sprintf必须引入
using namespace std;
int main(){
int ans=0;
for(int i=1;i<=2019;++i){
char s1[5];//字符串数组
sprintf(s1,"%d",i);//i放在字符串数组中
string s2(s1);//将字符串数组转为字符串
if(s2.find('9')!=string::npos){
ans++;
}
}
cout<<ans<<endl;
return 0;
}
方法2:
#include <iostream>
#include <sstream>
using namespace std;
void i2s(int num,string &str){
stringstream ss;
ss<<num;
ss>>str;
}
int main(){
int ans=0;
for(int i=1;i<=2019;++i){
string s;
i2s(i,s);
if(s.find('9')!=string::npos){
ans++;
}
}
cout<<ans<<endl;
return 0;
}