题解 | #学英语#
学英语
https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String[] unit = new String[] {"and", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred", "thousand", "million", "billion" }; String a; StringBuilder ans = new StringBuilder(); try { a = r.readLine(); } catch (IOException e) { throw new RuntimeException(e); } long n = 0; char[] chs = a.toCharArray(); int i = 0, j, j1, k, inx, l = chs.length; boolean b = false, andFg = true;//加and规则,百位为0,前面不加and,百位不为0,十位和个位有大于0的数,则加and,十位和个位之间不加and do { j = chs[i] - '0'; k = (l - i - 1) % 3; if (k == 2) { inx = (l - i - 1) / 3; if (b) ans.append(unit[inx + 29]).append(" "); b = true;//最高位是否加thousand,million,billion if (j == 0) andFg = true;//百位为0,与十位、个位之间不加and else { ans.append(unit[j]).append(" ").append(unit[28]).append(" "); andFg = false;//百位不为0,加and } i++; continue; } b = true; if (!andFg && j != 0) ans.append(unit[0]).append(" ");//当前位不为0,且andFg为false,加and if (k == 1 && j == 1) { j1 = chs[i + 1] - '0'; j1 += j * 10; ans.append(unit[j1]).append(" "); i += 2;//十位为1,跳过个位,到下一千位 continue; } else if (k == 1 && j > 1) { andFg = true;//十位大于2,和个位之间不加and ans.append(unit[j + 18]).append(" "); i++; continue; } if (j != 0) ans.append(unit[j]).append(" ");//个位不为0,加入当前数字 i++; } while (i < l); System.out.print(ans); } }