一.题目描述
【问题描述】小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。 请问,在 1 到 n 中,所有这样的数的和是多少?
【输入格式】输入一行包含两个整数 n。
【输出格式】输出一行,包含一个整数,表示满足条件的数的和。
二.代码
import java.util.Scanner;
public class test1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
for(int i=1;i<=n;i++){
if(check(i)){//满足数字由2,0,1,9任意一个或多个组成
sum=sum+i;//加上这个数,求和
}
}
System.out.println(sum);
}
public static boolean check(int n){
while(n>0){
int t=n%10;//先用一个数存最后一位数【也就是余数】
if(t==2||t==0||t==1||t==9){//如果有2或0或1或9其中任意一个
return true;
}
n=n/10;//除去刚刚判断过的最后一位数,再进行判断
}
return false;
}
}