问题描述
请统计某个给定范围[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。
public class AL_663 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int l=sc.nextInt();
int r=sc.nextInt();
int sum=0;
for (int i = l; i <=r; i++) {
String a=i+"";//转为字符串
for (int j = 0; j < a.length(); j++) {//逐个遍历
if (a.charAt(j)=='2'){
sum++;
}
}
}
System.out.println(sum);
}
}