题解 | #人民币转换#
人民币转换
http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
思路:分整数部分和小数部分分别定义两个函数进行处理,处理完成后去掉多余的零。数字转换很简单,主要是处理单位的转换。大概就这样。Code:
import java.util.*; public class RMBTransfer { static String[] unit = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"}; static Map<Integer, String> numMap = new HashMap<>(); static { numMap.put(0, "零"); numMap.put(1, "壹"); numMap.put(2, "贰"); numMap.put(3, "叁"); numMap.put(4, "肆"); numMap.put(5, "伍"); numMap.put(6, "陆"); numMap.put(7, "柒"); numMap.put(8, "捌"); numMap.put(9, "玖"); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String nStr = in.nextLine(); String integer = nStr.split("\\.")[0]; String decimal = nStr.split("\\.")[1]; String sbStr = handleInt(integer); String sb1Str = handleDecimal(decimal); StringBuffer sb = new StringBuffer(); if (sbStr.equals("人民币零") && !sb1Str.equals("")){ sb.append("人民币").append(sb1Str); }else{ sb.append(sbStr); if (sb1Str.equals("")){ sb.append("元整"); }else{ sb.append("元").append(sb1Str); } } System.out.println(sb.toString().replace("零零零", "零").replace("零零", "零").replace("壹拾", "拾").replace("零亿", "亿").replace("零万", "万").replace("零元", "元").replace("元零", "元").replace("角零", "角")); } } private static String handleDecimal(String decimal) { String[] unit1 = {"角", "分"}; StringBuffer sb = new StringBuffer(); int len = decimal.length(); if (decimal.equals("00")){ return ""; } for (int i = 0; i < len; i++) { int v = Integer.parseInt(decimal.charAt(i) + ""); sb.append(numMap.get(v)); if (v != 0){ sb.append(unit1[i]); } } return sb.toString(); } private static String handleInt(String integer) { if(integer == "0"){ return "人民币"; } int len = integer.length(); StringBuffer sb = new StringBuffer("人民币"); for (int i = 0; i < len; i++) { int v = Integer.parseInt(integer.charAt(i) + ""); sb.append(numMap.get(v)); if (v != 0 || len-i-1 == 4 && v == 0 || len-i-1 == 8 && v == 0){ sb.append(unit[len - i - 1]); } } return sb.toString(); } }