问题描述
输入正整数n,判断从1到n之中,数字1一共要出现几次。例如1123这个数,则出现了两次1。例如15,那么从1到15之中,一共出现了8个1。
输入格式
一个正整数n
输出格式
一个整数,表示1出现的资料
样例输入
15
样例输出
8
数据规模和约定
n不超过30000
解法一
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int cnt = 0;
for (int i = 0; i <= n; i++) {
int e = i / 10000;
int d = i % 10000 / 1000;
int a = i % 1000 / 100;
int b = i % 100 / 10;
int c = i % 10;
if (a == 1) cnt++;
if (b == 1) cnt++;
if (c == 1) cnt++;
if (d == 1) cnt++;
if (e == 1) cnt++;
}
System.out.println(cnt);
}
}
解法2:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int cnt = 0;
int j;
for (int i = 0; i <= n; i++) {
j=i;
while (j>0){
if (j%10==1) cnt++;
j/=10;
}
}
System.out.println(cnt);
}
}