题解 | #学英语#
学英语
https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
import java.io.IOException; import java.util.Scanner; import java.util.ArrayList; public class Main { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); String input = sc.nextLine(); ArrayList<String> list = new ArrayList<>(); // 将输入分成每三位一组的数字 int mod = input.length() % 3; if(mod != 0){ list.add(input.substring(0, mod)); } input = input.substring(mod); for(int i = 0; i < input.length(); i += 3){ String threeDigits = input.substring(i, i + 3); list.add(threeDigits); } // 因为输入的范围是1 ~ 2000000,所以可以这样简化判断 // 否则还是应该使用单索引指向两个数组下标的方法来进行匹配 if(list.size() == 3){ System.out.println(threeDigits(list.get(0)) + " million " + threeDigits(list.get(1)) + " thousand " + threeDigits(list.get(2))); } else if(list.size() == 2){ System.out.println(threeDigits(list.get(0)) + " thousand " + threeDigits(list.get(1))); } else { System.out.println(threeDigits(list.get(0))); } } // 三位数的数字和英文的转化 public static String threeDigits(String threeDigits){ // 判断是否是 0XX 或者是 00X这样的输入,将这样的输入转化为正常数字 if(threeDigits.length() == 3){ if(threeDigits.charAt(0) == '0'){ if(threeDigits.charAt(1) == '0'){ threeDigits = threeDigits.substring(2); } else { threeDigits = threeDigits.substring(1); } } } // 以下是正常三位数之内的数字的英文转化 String result = null; char[] nums = threeDigits.toCharArray(); String[] hundredAndUnit = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; String[] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; String[] tensUnit = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; if(nums.length == 1){ result = hundredAndUnit[nums[0] - '0']; } else if(nums.length == 2){ if(nums[0] == '1'){ result = tensUnit[nums[1] - '0']; } else { if(nums[1] != '0'){ result = tens[nums[0] - '0'] + " " + hundredAndUnit[nums[1] - '0']; }else { result = tens[nums[0] - '0']; } } } else { if(nums[1] == '1'){ result = hundredAndUnit[nums[0] - '0'] + " hundred and " + tensUnit[nums[2] - '0']; } else if(nums[1] == '0'){ if (nums[2] != '0'){ result = hundredAndUnit[nums[0] - '0'] + " hundred and " + hundredAndUnit[nums[2] - '0']; }else { result = hundredAndUnit[nums[0] - '0'] + " hundred"; } } else { result = hundredAndUnit[nums[0] - '0'] + " hundred and " + tens[nums[1] - '0'] + " " + hundredAndUnit[nums[2] - '0']; } } return result; } }