PAT 1002 写出这个数 (20) (Basic Level)
题目:
读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。
输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789
输出样例:
yi san wu
题目较简单,也不用判断输入的格式是否正确。代码如下(java):
1 import java.io.*; 2 import java.util.*; 3 public class Main 4 { 5 public static void main(String args[]){ 6 Scanner cin = new Scanner(System.in); 7 while(cin.hasNext()){ 8 String inputString = cin.next(); 9 int sum = 0; 10 for(int i = 0;i < inputString.length();i++){ 11 sum += Integer.parseInt(inputString.substring(i, i+1)); 12 } 13 System.out.println(toString(sum)); 14 } 15 } 16 public static String toString(int n){ 17 String output = new String(); 18 String s = Integer.toString(n); 19 for(int i = 0;i < s.length();i++){ 20 if('0' == s.charAt(i) && i != 0) 21 output += " " + "ling"; 22 else if('1' == s.charAt(i)){ 23 if(0 == i) 24 output += "yi"; 25 else 26 output += " " + "yi"; 27 } 28 else if('2' == s.charAt(i)){ 29 if(0 == i) 30 output += "er"; 31 else 32 output += " " + "er"; 33 } 34 35 else if('3' == s.charAt(i)){ 36 if(0 == i) 37 output += "san"; 38 else 39 output += " " + "san"; 40 } 41 42 else if('4' == s.charAt(i)){ 43 if(0 == i) 44 output += "si"; 45 else 46 output += " " + "si"; 47 } 48 49 else if('5' == s.charAt(i)){ 50 if(0 == i) 51 output += "wu"; 52 else 53 output += " " + "wu"; 54 } 55 else if('6' == s.charAt(i)){ 56 if(0 == i) 57 output += "liu"; 58 else 59 output += " " + "liu"; 60 } 61 62 else if('7' == s.charAt(i)){ 63 if(0 == i) 64 output += "qi"; 65 else 66 output += " " + "qi"; 67 } 68 69 else if('8' == s.charAt(i)){ 70 if(0 == i) 71 output += "ba"; 72 else 73 output += " " + "ba"; 74 } 75 76 else if('9' == s.charAt(i)){ 77 if(0 == i) 78 output += "jiu"; 79 else 80 output += " " + "jiu"; 81 } 82 83 } 84 return output; 85 86 87 } 88 }