机试题记录-整数分解和阿拉伯数字转中文读法

整数分解

    public static void main(String[] args) {
        resolve(4,1);
    }

    public static List res = new ArrayList<>();
    public static void resolve(int n, int start){
        if (n <= 0) {
            for (int i = 0; i < res.size(); i++) {
                System.out.print(res.get(i)+" ");
            }
            System.out.println();
        }
        
        for (int i = start; i <= n; i++) {
            res.add(i);
            resolve(n-i, i);
            res.remove(res.size()-1);
        }
    }

阿拉伯数字转中文读法

    public static final int ITEM_LENGTH = 4;
    
    public static String[] chineseNumber = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    
    public static String[] chineseUnite = {"", "十", "百", "千"};

    public static void numToChinese(String number) {
        boolean isNegtive = false;
        if (number.startsWith("-")) {
            number = number.substring(1);
            isNegtive = true;
        }
        StringBuilder sb = new StringBuilder();
        int len = number.length();
        int itemCount = 0;
        while (len > 0) {
            int start = (len - ITEM_LENGTH) > 0 ? len - ITEM_LENGTH : 0;
            String item = number.substring(start, len);
            String itemChinese = processItem2Chinese(item, itemCount);
            sb.insert(0, itemChinese);
            len -= ITEM_LENGTH;
            itemCount++;
        }

        if (isNegtive) {
            sb.insert(0, "负");
        }
        

        String result = washString(sb.toString());
        
        System.out.println(result);
    }
    
    public static String washString(String str) {
        if (str.startsWith("一十")) {
            str = str.substring(1);
        }

        if (str.length() > 1 && str.endsWith("零")) {
            str = str.substring(0, str.length() - 1);
        }

        if (str.contains("零零")) {
            str = str.replace("零零", "零");
        }
        return str;
    }

    private static String processItem2Chinese(String item, int count) {
        boolean isPureZero = true;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < item.length(); i++) {
            int currentNum = Integer.valueOf(item.charAt(item.length() - i - 1) + "");
            if (currentNum == 0) {
                if ((sb.length() != 0 && sb.charAt(0) != '零') || (item.length()==1)) {
                    sb.insert(0, chineseNumber[currentNum]);
                }
            } else {
                isPureZero = false;
                sb.insert(0, chineseUnite[i]);
                sb.insert(0, chineseNumber[currentNum]);
            }
        }

        if (count == 2 || count == 4) {
            sb.append("亿");
        }

        if (count == 1 || count == 3 ||count == 5) {
            if (!isPureZero) {
                sb.append("万");
            } else {
                sb.append("零");
            }
        }
        return sb.toString();
    }

你可能感兴趣的:(leetcode)