整数的英语表示

给定一个整数,打印该整数的英文描述。

示例 1:

输入: 123
输出: "One Hundred Twenty Three"
示例 2:

输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:

输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:

输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

package cn.tiger.funny;

import java.util.ArrayList;
import java.util.List;


public class NumberToWords {
    private final String HUNDRED = "Hundred ";
    private final String[] UNIT= {
            "", 
            "Thousand ", 
            "Million ", 
            "Billion "};
    private final String[] NUMBER= {
            "", 
            "One ", 
            "Two ",
            "Three ",
            "Four ", 
            "Five ", 
            "Six ", 
            "Seven ", 
            "Eight ", 
            "Nine "};
    private final String[] NUMBER_ADD_TEN= {
            "Ten ", 
            "Eleven ",
            "Twelve ",
            "Thirteen ", 
            "Fourteen ", 
            "Fifteen ", 
            "Sixteen ", 
            "Seventeen ", 
            "Eighteen ", 
            "Nineteen "};
    private final String[] TENS= {
            "", 
            "",
            "Twenty ",
            "Thirty ", 
            "Forty ", 
            "Fifty ", 
            "Sixty ", 
            "Seventy ", 
            "Eighty ", 
            "Ninety "};
    
    /**
     * 给定一个整数,打印该整数的英文描述。
     * @param num
     * @return
     */
    public String numberToWords(int num) {
        if( num == 0 ) {
            return "Zero";
        }
        String words = "";
        List<Integer> ints = getIntGroup(num);
        for (int i = 0; i < ints.size(); i++) {
            String smallNumber = smallNumberToWords(ints.get(i));
            if(!smallNumber.isEmpty()) {
                words = smallNumber + UNIT[i] + words;
            }
        }
        return words.isEmpty()?"":words.substring(0, words.length()-1);
    }
    
    /**
     * 将数字每三位分组
     * @param num 
     * @return
     */
    private List<Integer> getIntGroup(int num) {
        List<Integer> ints = new ArrayList<Integer>();
        while( num/1000>0 ) {
            ints.add(num%1000);
            num = num/1000;
        }
        ints.add(num);
        return ints;
    }
    
    /**
     * 将三位数数字转成words
     * @param num 三位数一下(包含)数字
     * @return
     */
    private String smallNumberToWords(int num) {
        String words = "";
        if(num/100 != 0) {
            words += NUMBER[num/100] + HUNDRED;
        }
        num = num%100;
        if(num/10 == 0) {
            words += NUMBER[num%10];
        } else if (num/10 == 1) {
            words += NUMBER_ADD_TEN[num%10];
        } else {
            words += TENS[num/10] + NUMBER[num%10];
        }
        return words;
    }
}
    

 

posted @ 2021-01-05 11:12  预言2018  阅读(377)  评论(0)    收藏  举报