原题链接:
https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805430595731456&page=0
注意点:
- 这道题需要找规律,可以使用打表法,即通过暴力的方法计算出当N比较小时的结果(我这里计算出来当N在0-299时对应的输出),通过大量数据寻找规律。
- 我这里的处理思路是从个位开始,计算小于等于N时,该位上为1的可能性。举例说明:当N为210,先看个位0,个位上为1小于等于210的有001,011,021,031,...,201,一共21个;再看十位1,十位上为1且小于等于210的有01_(010,011,...,019)(10个),11_(10个),210(1个);最后看百位2,百位上为1且小于等于210的有1__(100个)。21+10+10+1+100=142为最终输出。
代码:
#include <iostream>
using namespace std;
#define endl '\n'
int N;
//int cnt[300];
int res = 0;
//int findOne(int x) {
// int res = 0;
// while (x != 0) {
// int last = x % 10;
// x /= 10;
// if (last == 1) {
// res++;
// }
// }
// return res;
//}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
/*for (int i = 1; i < 300; i++) {
cnt[i] = cnt[i - 1] + findOne(i);
}*/
int source = N;
int last = 0;
int radix = 1;
while (N != 0) {
last = N % 10;
N /= 10;
res += N*radix;
if (last > 1) {
res += radix;
}
else if (last == 1) {
res += source % radix + 1;
}
radix *= 10;
}
cout << res;
return 0;
}