题解 | #人民币转换#

人民币转换

https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b

import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Map<Integer, String> numMap = new HashMap<>();
        Map<Integer, String> unitMap = new HashMap<>();
        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, "玖");
        numMap.put(0, "零");
        unitMap.put(1, "拾");
        unitMap.put(2, "佰");
        unitMap.put(3, "仟");
        unitMap.put(5, "万");
        unitMap.put(9, "亿");

        String money = in.nextLine();
        String[] arr = money.split("\\.");
        char[] intChs = arr[0].toCharArray();//整数
        int len = intChs.length;
        StringBuffer sb = new StringBuffer();
        sb.append("人民币");
        //整数为0不显示‘元’
        if (!"0".equals(arr[0])) {
            //处理整数
            for (int i = len; i > 0; i--) {
                int num = intChs[len - i] - '0';
                String cha = numMap.get(num);
                sb.append(cha);
                if ((i - 1) % 4 == 0 && (i - 1) > 0) { //单位:万、亿
                    String unit = "";
                    if (i > 12) { //万亿
                        unit = unitMap.get(i - 8);
                    } else {
                        unit = unitMap.get(i);
                    }
                    sb.append(unit);
                } else if ((i - 1) > 0 && num != 0) { //单位:十、百、千
                    String unit = unitMap.get((i - 1) % 4);
                    sb.append(unit);
                }
            }
            sb.append("元");
        }

        //处理小数点后
        if (arr.length > 1) {
            char[] diciChs = arr[1].toCharArray();
            if (diciChs[0] == '0' && diciChs[1] == '0') {
                sb.append("整");
            } else if (diciChs[0] == '0') {
                sb.append(numMap.get(diciChs[1] - '0') + "分");
            } else {
                sb.append(numMap.get(diciChs[0] - '0') + "角");
                if (diciChs[1] != '0') {
                    sb.append(numMap.get(diciChs[1] - '0') + "分");
                }
            }
        } else {
            sb.append("整");
        }



        String res = sb.toString().replaceAll("[零]+", "零").replace("零亿",
                     "亿").replace("零万", "万")
                     .replace("零元", "元").replace("壹拾", "拾");
        System.out.println(res);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务