算法标签:枚举
题目描述
小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。
请问,在 1 到 n 中,所有这样的数的和是多少?
输入格式
共一行,包含一个整数 n。
输出格式
共一行,包含一个整数,表示满足条件的数的和。
数据范围
1≤n≤10000
输入样例:
40
输出样例:
574
思路
我们现在求得是在 1 到 n 中,所有这样的数的和是多少
由于数据小,我们只需要暴力枚举,然后每个数递归判断就可以了。
C++ 代码
枚举
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int res=0,x=0;
for(int i=1;i<=n;i++)
{
x=i;
while(x)
{
int t=x%10;
if(t==2||t==0||t==9||t==1)//一个数满足就计算一次
{
res+=i;
break;
}
x/=10;
}
}
cout<<res;
return 0;
}
递归
#include<iostream>
int n,res;
void check(int x,int u)
{
if(!x)return ;
if(x%10==2||x%10==0||x%10==9||x%10==1){res+=u;return;}
check(x/10,u);
}
int main()
{
while(std::cin>>n,n){int k=n;check(n--,k);}
std::cout<<res;
return 0;
}
20201011
#include<iostream>
using namespace std;
int ans,n;
bool check(int n){
while(n){
int tmpn = n%10;
if(tmpn==2||tmpn==0||tmpn==1||tmpn==9)
return true;
n/=10;
}
return false;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
if(check(i))ans+=i;
}
cout<<ans<<endl;
return 0;
}