题解 | #学英语#
学英语
https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
分不同的函数处理:
1.处理个位和十位
2.处理百位
import javax.print.attribute.standard.RequestingUserName; import java.util.Scanner; public class Main { static String[] oneToNineteen = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; static String[] twentyToNinety = {"","","twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; static String[] threeUnit = {" ","thousand ","million ","billion "}; public static String oneAndTen(int num) { if(num==0) return ""; if (num <= 19) return oneToNineteen[num] +" "; return twentyToNinety[num/10] + (num%10==0?"":" ") + oneToNineteen[num%10] +" "; } public static String hundred(int num, int partOneTenPlace) { StringBuffer sb = new StringBuffer(); int partHundredPlace = num % 10; if(partHundredPlace!=0){ sb.append(oneToNineteen[partHundredPlace]).append(" hundred "); if(partOneTenPlace!=0){ sb.append("and "); } } return sb.toString(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 long number = in.nextLong(); StringBuffer sb = new StringBuffer(); int threeUnitIdx = 0; while(number>0){ int partOneTenPlace = (int) (number % 100); String partOneAndTen = oneAndTen(partOneTenPlace); String partHundred = hundred((int) (number /= 100), partOneTenPlace); String partThreeUnit = threeUnit[threeUnitIdx++]; sb.insert(0,partThreeUnit).insert(0,partOneAndTen).insert(0,partHundred); number /= 10; } System.out.println(sb); } }