题解 | #学英语#
学英语
https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
这道题思路很简单,就是需要注意的细节太多。
import java.util.*; import java.lang.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case long a = in.nextLong(); String[] sa = String.format("%,d", a).split(",");//使用格式化函数将输入按逗号分隔 int sal = sa.length; String out = ""; //对每个部分转化处理去掉前缀为0的部分,00X->X,0XX->XX,000->0 for(int i=0;i<sal;i++){ sa[i] = String.valueOf(Integer.parseInt(sa[i])); } //对逗号中间的部分分别做处理,创建treatHundred用于处理三位以下的读法 Main m = new Main(); if (sal == 3) { out = m.treatHundred(sa[0])+" million "+m.treatHundred(sa[1])+" thousand "+m.treatHundred(sa[2]); } else if (sal == 2) { out = m.treatHundred(sa[0])+" thousand "+m.treatHundred(sa[1]); }else if(sal==1){ out = m.treatHundred(sa[0]); } //去掉多余的空格后输出 out = out.replaceAll(" "," "); System.out.println(out.trim()); } } //处理三位数字的读法 public String treatHundred(String s) { String[] dict = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; String[] dict1 = {"", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; String[] dict2 = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; String out=""; switch (s.length()) { case 1: out = dict[Integer.parseInt(s)]; break; case 2: int x = Integer.parseInt(s) / 10; int y = Integer.parseInt(s) % 10; if (x == 1 && y!=0) { out = dict1[y]; } else if (x > 1) { out = dict2[x] + " " + dict[y]; }else if(s.equals("10")){ out = "ten"; } break; case 3: int j = Integer.parseInt(s) / 100; //取百位 int k = (Integer.parseInt(s) % 100) / 10; //取十位 int l = (Integer.parseInt(s) % 100) % 10; //取个位 if (k == 1 && l>0) { out = dict[j] + " hundred and " + dict1[l]; } else if (k > 1) { out = dict[j] + " hundred and " + dict2[k] + " " + dict[l]; } else if (k == 0 && l!=0) { out = dict[j] + " hundred and " + dict[l]; }else if(k==0 && l==0){ out = dict[j] + " hundred"; }else if(k==1 && l==0){ out = dict[j] + " hundred and "+"ten"; } break; } return out; } }