题目描述
小明对数位中含有 2 、 0 、 1 、 9 2、0、1、9 2、0、1、9 的数字很感兴趣(不包括前导 0 0 0),在 1 1 1 到 40 40 40 中这样的数包括 1 、 2 、 9 、 10 1、2、9、10 1、2、9、10 至 32 、 39 32、39 32、39 和 40 40 40,共 28 28 28 个,他们的和是 574 574 574。
请问,在 1 1 1 到 n n n 中,所有这样的数的和是多少?
输入格式
共一行,包含一个整数 n n n。
输出格式
共一行,包含一个整数,表示满足条件的数的和。
数据范围
1 ≤ n ≤ 10000 1 \le n \le 10000 1≤n≤10000
输入样例:
40
输出样例:
574
思路
水题,挨个遍历每个数,然后判断是否保护2、0、1、9即可。
代码
#include <iostream>using namespace std;int n;bool check(int x)
{while ( x ){int t = x % 10;if ( t == 2 || !t || t == 1 || t == 9 ) return true;x /= 10;}return false;
}int main()
{cin >> n;int res = 0;for ( int i = 1; i <= n; i ++ ) if ( check(i) ) res += i;cout << res << endl;return 0;
}