试题 F:特别数的和

时间限制:1.0s     内存限制:256.0MB     本题总分:15 分

【问题描述】

       小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。 请问,在 1 到 n 中,所有这样的数的和是多少?

【输入格式】

       输入一行包含一个整数 n。

【输出格式】

       输出一行,包含一个整数,表示满足条件的数的和。

【样例输入】

40

【样例输出】

574

【评测用例规模与约定】

对于 20% 的评测用例,1≤n≤10。
对于 50% 的评测用例,1≤n≤100。
对于 80% 的评测用例,1≤n≤1000。
对于所有评测用例,1≤n≤10000。

 

思路:从1~n循环,检测该数中有没有2、0、1、9,有的话就累加,由于数据范围不大,就没有打表不知道会不会超时。

参考代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
 
bool check(int n)
{
	while(n)
	{
		int t=n%10;
		if(t==2||t==0||t==1||t==9)
			return true;
		n/=10;
	}
	return false;
}
 
int main()
{
	int n,ans=0;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		if(check(i))
			ans+=i;
	}
	cout<<ans<<endl;
	return 0;
}