AC代码:
import java.util.*; /** * @author CC11001100 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(toPinYin(sum(s))); } private static int sum(String s){ int res = 0; for(int i=0; i<s.length(); i++){ res += s.charAt(i) - '0'; } return res; } private static Map<Integer, String> map = new HashMap<>(); static{ map.put(0, "ling"); map.put(1, "yi"); map.put(2, "er"); map.put(3, "san"); map.put(4, "si"); map.put(5, "wu"); map.put(6, "liu"); map.put(7, "qi"); map.put(8, "ba"); map.put(9, "jiu"); } private static String toPinYin(int n){ if(n<=9) return map.get(n); else return toPinYin(n/10) + " " + map.get(n % 10); } }
或者可以使用数组下标来对应,就不用map了,也是能够随机访问取到:
import java.util.*; /** * @author CC11001100 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(toPinYin(sum(s))); } private static int sum(String s){ int res = 0; for(int i=0; i<s.length(); i++){ res += s.charAt(i) - '0'; } return res; } private static String[] mapping = new String[]{"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu" }; private static String toPinYin(int n){ if(n<=9) return mapping[n]; else return toPinYin(n/10) + " " + mapping[n%10]; } }
题目来源: https://www.nowcoder.com/pat/2/problem/4068
.