安徽网站开发培训,北京免费网站建设模板下载,wordpress 特效,啥叫优化题目描述
小明对数位中含有2、0、1、9 的数字很感兴趣#xff08;不包括前导0#xff09; 在1到40中这样的数包括1、2、9、10 至32、39 和40#xff0c;共28 个#xff0c;他们的和是574。 请问#xff0c;在1到n 中#xff0c;所有这样的数的和是多少#xff1f;
输入…题目描述
小明对数位中含有2、0、1、9 的数字很感兴趣不包括前导0 在1到40中这样的数包括1、2、9、10 至32、39 和40共28 个他们的和是574。 请问在1到n 中所有这样的数的和是多少
输入
输入一个正整数n(1n10000)
解法一 代码如下
#include iostream
#include sstreamusing namespace std;bool check(int x) {stringstream ss;ss x;string s;ss s;for (int i 0; i s.size(); i) {if (s[i] 2 || s[i] 0 || s[i] 1 || s[i] 9)return true;}return false;
}int main() {int n;cin n;ios::sync_with_stdio(false);cin.tie(0);int ans 0;for (int i 1; i n; i) {if (check(i)) {ans i;}}cout ans endl;return 0;
}解法二更快 代码如下
#include iostream
using namespace std;bool check(int x) {while (x) {int c x % 10;if (c 2 || c 0 || c 1 || c 9)return true;x x / 10;}return false;
}int main() {ios::sync_with_stdio(false);cin.tie(0);int n;int ans 0;cin n;for (int i 1; i n; i) {if (check(i)) {ans i;}}cout ans endl;return 0;
}