【问题描述】
小明对数位中含有 2、0、1、9 的数字很感兴趣,在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574,平方和是 14362。
注意,平方和是指将每个数分别平方后求和。
请问,在 1 到 2019 中,所有这样的数的平方和是多少?
思路:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
long long sum = 0;
int temp;
for(int i=0; i<=2019; i++){
temp = i;
//遍历i中每一位,直至i中所有位遍历完成
while(temp != 0){
//判断当前个位是否含 2 0 1 9
if(temp%10 == 2 || temp%10 == 0 || temp%10 == 1 || temp %10 == 9){
sum += pow(i, 2);
break;
}
//移位,变换当前个位
temp /= 10;
}
}
printf("sum = %lld", sum);
return 0;
结果:
总结:
本题的关键在于提取所遍历数中的每一位(通过while循环),判断其中是否含有 2 0 1 9 这四个数