题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
import java.util.*; import java.util.stream.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { String[] cnNames = "零、壹、贰、叁、肆、伍、陆、柒、捌、玖".split("、"); String[] levelName = "拾、佰、仟".split("、"); Scanner in = new Scanner(System.in); String[] line = in.nextLine().split("\\."); List<Integer> numPartList = Arrays.stream(line[0].split("")).map( x -> Integer.parseInt(x)).collect(Collectors.toList()); Collections.reverse(numPartList); List<String> output = new ArrayList<>(); for (int i = 0; i < numPartList.size() / 4 + 1; i++) { if (4 * i < numPartList.size()) { if (i == 1) { output.add("万"); } else if (i == 2) { output.add("亿"); } } for (int k = 0; k < 4 && 4 * i + k < numPartList.size(); k++) { int num = numPartList.get(4 * i + k); if (num == 0 && (k == 0 || numPartList.get(4 * i + k - 1) == 0)) { continue; } String cnName = cnNames[num]; String outCnName = cnName; if (k > 0 && num > 0) { String itemLevelName = levelName[k - 1]; if ( "壹".equals(cnName) && "拾".equals(itemLevelName)) { outCnName = itemLevelName; } else { outCnName += itemLevelName; } } output.add(outCnName); } } Collections.reverse(output); if (!output.isEmpty()) { output.add("元"); } List<String> secondPartOutPut = new ArrayList<>(); if (line.length == 2) { int[] secondPart = Arrays.stream(line[1].split("")).mapToInt( x -> Integer.parseInt(x)).toArray(); for (int i = 0; i < 2 && i < secondPart.length; i++) { int num = secondPart[i]; if (num != 0) { String cnName = cnNames[num]; if (i == 0) { cnName += "角"; } else if (i == 1) { cnName += "分"; } secondPartOutPut.add(cnName); } } } if (secondPartOutPut.isEmpty()) { output.add("整"); } else { output.addAll(secondPartOutPut); } System.out.println("人民币" + String.join("", output)); in.close(); } }