问题描述
请统计某个给定范围[L, R]的所有整数中,数字2 出现的次数。 比如给定范围[2, 22],数字2 在数2 中出现了1 次,在数12 中出现1 次,在数20 中出现1 次,在数21 中出现1 次,在数22 中出现2 次,所以数字2 在该范围内一共出现了6次。
输入格式
输入共1 行,为两个正整数L 和R,之间用一个空格隔开。
输出格式
输出共1 行,表示数字2 出现的次数。
样例输入
Sample Input1:
2 22
Sample Input2:
2 100
样例输出
Sample Output1:
6
Sample Output2:
20
数据规模和约定
1 ≤ L ≤ R≤ 10000。
请统计某个给定范围[L, R]的所有整数中,数字2 出现的次数。 比如给定范围[2, 22],数字2 在数2 中出现了1 次,在数12 中出现1 次,在数20 中出现1 次,在数21 中出现1 次,在数22 中出现2 次,所以数字2 在该范围内一共出现了6次。
输入格式
输入共1 行,为两个正整数L 和R,之间用一个空格隔开。
输出格式
输出共1 行,表示数字2 出现的次数。
样例输入
Sample Input1:
2 22
Sample Input2:
2 100
样例输出
Sample Output1:
6
Sample Output2:
20
数据规模和约定
1 ≤ L ≤ R≤ 10000。
import java.util.*;
public class Main5 {
public static int L, R;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
L = sc.nextInt();
R = sc.nextInt();
int sum = 0;
for (int i = L; i <= R; i++) {
int tmp = i; //依次判断每一位数字是否是2
while (tmp > 0) {
if (tmp % 10 == 2) {
sum++;
}
tmp /= 10;
}
}
System.out.println(sum);
}
}