數字2的統計

問題描述
  請統計某個給定範圍[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);

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章