题目描述
小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。
请问,在 1 到 n 中,所有这样的数的和是多少?
输入格式:
输入一行包含一个整数 n。
输出格式:
输出一行,包含一个整数,表示满足条件的数的和。
输入样例:
在这里给出一组输入。例如:
40
输出样例:
在这里给出相应的输出。例如:
574
思路
简单题争取一遍过,将数字转化为字符串搜索一遍即可,(注意方法使用)
代码实现
package practise.bluecompetion2019;
import java.util.Scanner;
public class 特别数的和 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int sum=0;
for (int i = 1; i <=n; i++) {
String test=i+"";
if (test.indexOf("2")!=-1||test.indexOf("0")!=-1||test.indexOf("1")!=-1||test.indexOf("9")!=-1){
sum+=i;
}
}
System.out.println(sum);
}
}