The Number In Words

http://www.lintcode.com/en/problem/the-number-in-words/

public class Solution {
    String[] unit1 = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
            "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    String[] unit2 = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

    /*
     * @param : the number
     * @return: the number in words
     */
    public String convertWords(int number) {
        // Write your code here
        if (number == 0) {
            return "zero";
        }
        String[] unit = {"", "thousand", "million", "billion", "trillion"};

        StringBuilder sb = new StringBuilder();
        for (int i = 0; number > 0; i++) {
            if (number % 1000 > 0) {
                sb.insert(0, get3(number % 1000) + " " + unit[i] + " ");
            }
            number /= 1000;
        }
        return sb.toString().trim();
    }

    private String get3(int i) {
        int i1 = i / 100;
        int i2 = i % 100;
        String temp = "";
        if (i1 > 0) {
            temp = unit1[i1 - 1] + " hundred ";
        }
        temp += get2(i2);
        return temp;
    }

    private String get2(int i2) {
        String temp = "";
        if (i2 < 20 && i2 > 0) {
            return unit1[i2 - 1];
        }
        int i = i2 / 10;
        int i1 = i2 % 10;
        if (i > 0) {
            temp = unit2[i - 2];
        }
        if (i1 > 0) {
            temp += " " + unit1[i1 - 1];
        }
        return temp;
    }
}

你可能感兴趣的:(The Number In Words)