Java程序练习-计数的梦


计数的梦
时间限制: 10000ms内存限制: 1024kB
描述
Bessie 处于半梦半醒的状态。过了一会儿,她意识到她好像在数羊,不能入睡。Bessie的大脑反应灵敏,仿佛真实地看到了她数过的一个又一个数。她开始注意每一个数码:每一个数码在计数的过程中出现过多少次?
给出两个整数 M 和 N (1 <= M <= N <= 2,000,000,000 以及 N-M <= 500,000),求每一个数码出现了多少次。
例如考虑序列 129..137: 129, 130, 131, 132, 133, 134, 135, 136, 137。统计后发现:
1x0 1x5
10x1 1x6
2x2 1x7
9x3 0x8
1x4 1x9
输入
共一行,两个用空格分开的整数 M 和 N
输出
共一行,十个用空格分开的整数,分别表示数码(0..9)在序列中出现的次数。
样例输入
129 137
样例输出
1 10 2 9 1 1 1 1 0 1

参考代码
  1. /* 
  2.  * Dream Counting 2011-10-1 1:28PM Eric Zhou 
  3.  */  
  4. import java.io.BufferedReader;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. public class Main {  
  8.     public static int cnt[] = new int[10];  
  9.     public static void main(String[] args) throws IOException {  
  10.         BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));  
  11.         String sn[] = cin.readLine().split(" ");   
  12.         int a = Integer.parseInt(sn[0]);  
  13.         int b = Integer.parseInt(sn[1]);  
  14.         int i = 0;  
  15.         for(i = a;i <= b;++ i){  
  16.             setcnt(i);  
  17.         }  
  18.         for(i = 0;i < 10;++ i)  
  19.             System.out.print(cnt[i]+" ");  
  20.         System.out.println();  
  21.     }  
  22.     private static void setcnt(int n) {  
  23.         if(n == 0)  
  24.             cnt[0] ++;  
  25.         while(n > 0){  
  26.             int p = n % 10;  
  27.             cnt[p] ++;  
  28.             n /= 10;  
  29.         }  
  30.     }  
  31. }  

相关内容