题解 | #分治学英语#
学英语
https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
import java.util.Scanner; /*** *** 利用每三位一组的特性,在数字表达上从高位到低位(字符串从左到右)的顺序开始学,在整体上按照""、"thousand"、"million"、"billion"每三位进行分配,分配的原则是碰到组中的最低位(0)进行分配。 注意点: 因为字符从左到右是0到len-1的顺序,但是在数字中要转换一下对应位数分组位:(str.length() - 1 - i) / 3, (str.length() - 1 - i) % 3每组中俄位数。剩下就是里面的分支判断了,感觉这样写下来比较清晰,好理解。 ***/ // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static String[] spk_bmt = {"", "thousand", "million", "billion"}; static String[] spk_nums_ge = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; static String[] spk_nums_shi = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; static String[] spk_nums_one_shi = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLong()) { // 注意 while 处理多个 case Long num = in.nextLong(); System.out.println(speakNum(num)); } } public static String speakNum(Long num) { String spk_ans = ""; String str = String.valueOf(num); int len = str.length(); if (len == 1) { return spk_nums_ge[Integer.valueOf(str)]; } for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); int bit_num = Character.getNumericValue(c); String speak_num = ""; int part = (str.length() - 1 - i) / 3; if ((str.length() - 1 - i) % 3 == 0 ) { // 个位 if (i - 2 >= 0 && str.charAt(i - 1) == '0' && str.charAt(i - 2) == '0' && str.charAt(i) == '0') { continue; } speak_num = spk_nums_ge[bit_num]; speak_num = speak_num + " " + spk_bmt[part] + " "; } else if ((str.length() - 1 - i) % 3 == 2) { // 百位 speak_num = spk_nums_ge[bit_num]; if (str.charAt(i) != '0') { speak_num = speak_num + " hundred "; if (str.charAt(i + 1) != '0' || str.charAt(i + 2) != '0') { speak_num = speak_num + "and "; } } } else if ((str.length() - 1 - i) % 3 == 1) { //十位 if (str.charAt(i) == '1') { speak_num = spk_nums_one_shi[Character.getNumericValue(str.charAt(i + 1))]; i++; } else { speak_num = spk_nums_shi[bit_num] + " "; } } spk_ans = spk_ans + speak_num; } return spk_ans.replaceAll(" ", " "); } }