Integer to English Words

https://www.lintcode.com/problem/integer-to-english-words/description

public class Solution {
    /**
     * @param num: a non-negative integer
     * @return: english words representation
     */
    public String numberToWords(int num) {
        // Write your code here
        String res = "";
        String[] v = {" Thousand ", " Million ", " Billion "};
        int index = -1;
        while (num > 0) {
            int i = num % 1000;
            String string = getString(i);
            if (index >= 0) {
                res = string + v[index] + res;
            } else {
                res = string + res;
            }
            index++;
            num /= 1000;
        }
        if (res.isEmpty()) {
            return "Zero";
        }
        return res;
    }

    private String getString(int n) {
        String[] v1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        String[] v2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        int b = n / 100;
        int s = (n % 100) / 10;
        int g = n % 10;
        String res = "";
        if (s >= 2) {
            res = v2[s] + " " + v1[g];
        } else {
            res = v1[n % 100];
        }
        if (b > 0) {
            res = v1[b] + " Hundred " + res;
        }
        return res;
    }
}

你可能感兴趣的:(Integer to English Words)