题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
import java.util.Scanner; // 注意类名必须为 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 // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } String[] nums = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"}; String[] units = {"元", "万", "亿"}; String line = in.nextLine(); String yuan = line.split("\\.")[0]; int len = yuan.length(); String jiaoFen = line.split("\\.")[1]; int count = 0; String temp = yuan; String result = ""; while (temp.length() > 0) { int tempLen = temp.length(); if (tempLen > 4) { result = convert(temp.substring(tempLen - 4, tempLen), nums) + units[count++] + result; temp = temp.substring(0, tempLen - 4); } else { result = convert(temp, nums) + units[count++] + result; temp = ""; } } result.replaceAll("零零", "零"); if (result.startsWith("零")) { result = result.substring(1); } if (jiaoFen.charAt(0) != '0') { result = result + nums[jiaoFen.charAt(0) - '0'] + "角"; } if (jiaoFen.charAt(1) != '0') { result = result + nums[jiaoFen.charAt(1) - '0'] + "分"; } if (Long.parseLong(yuan) == 0) { result = result.substring(1); } System.out.print("人民币" + result); } private static String convert(String str, String[] nums) { if ("0000".equals(str)) { return ""; } int len = str.length(); int n = Integer.parseInt(str); int ge = n % 10; int shi = (n / 10) % 10; int bai = (n / 100 % 10); int qian = n / 1000; String result = ""; if (qian != 0) { result = nums[qian] + "仟"; } else { result = "零"; } if (bai != 0) { result = result + nums[bai] + "佰"; } else if (bai == 0 && qian != 0) { result = result + "零"; } if (shi != 0) { if (shi == 1) { result = result + "拾"; } else { result = result + nums[shi] + "拾"; } } else if (shi == 0 && bai != 0) { result = result + "零"; } if (ge != 0) { result = result + nums[ge]; } return result; } }