LeetCode-Integer to English Words

LiBlog發表於2016-09-10

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Solution:

BE CAREFUL: all kinds of corner cases

public class Solution {
    String[] suffixs = new String[]{"","Thousand", "Million","Billion"};
    String[] tens = new String[]{"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty", "Ninety"};
    String[] tenTwenty = new String[]{"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    String[] singles = new String[]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
    
    public String numberToWords(int num) {
        if (num==0) return "Zero";
        
        StringBuilder builder = new StringBuilder();
        int base = 1000;
        int index = 0;
        while (num!=0){
            int sectionNum = num%base;
            num = num / base;
            addSection(builder,sectionNum,suffixs[index++]);
        }
        return builder.toString().trim();
    }
    
    public void addSection(StringBuilder builder, int sectionNum, String suffix){
        if (sectionNum==0){
            return;
        }
        
        builder.insert(0," "+suffix);
        
        int hundreds = sectionNum / 100;
        int left = sectionNum % 100;
        
        if (left > 0){
            if (left<10){
                builder.insert(0,singles[left]).insert(0," ");
            } else if (left>=10 && left < 20){
                builder.insert(0,tenTwenty[left-10]).insert(0," ");
            } else {
                String temp = " " + tens[left/10] + ((left%10==0) ? "" : (" " + singles[left%10]));
                builder.insert(0,temp);
            }
        }
        
        if (hundreds>0){
            String temp = " " + singles[hundreds] + " Hundred";
            builder.insert(0,temp);
        }
    }
}

 

相關文章