问题:
小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。
请问,在 1 到 n 中,所有这样的数的和是多少?
法1:使用for循环
#include <stdio.h>
int main()
{
int a = 1;
int b, c = 0;
long long int sum = 0;
for (a = 1; a <= 2019; a++) {
for (b = a; b > 0; b = b / 10) {
c=b%10;
if (c == 2 || c == 0 || c == 1 || c == 9) {
sum += a * a;
break;
}
}
}
printf("%lld", sum);
return 0;
}
法2:使用while循环
#include <stdio.h>
int main() {
int a = 1;
int b = 0;
int c = 0;
long long int sum = 0;
while (a <= 2019) {
b = a;
while (b > 0)
{
c = b % 10;
if (c == 2 || c == 0 || c == 1 || c == 9) {
sum += a * a;
break;
}
b = b / 10;
}
a++;
}
printf("%lld", sum);
return 0;
小白的解题方法罢了,适合初学者,我只是做个笔记啦,欢迎大佬点评