273. Integer to English Words

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

Example 1:

Input:
 123

Output:
 "One Hundred Twenty Three"

Example 2:

Input:
 12345

Output:
 "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input:
 1234567

Output:
 "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input:
 1234567891

Output:
 "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

Solution

(1) Java

class Solution {
    public String numberToWords(int num) {
        int[] nums = new int[]{1000000000, 1000000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
        String[] strs = new String[]{"Billion", "Million", "Thousand", "Hundred", "Ninety", "Eighty", "Seventy", "Sixty", "Fifty", "Forty", "Thirty", "Twenty", "Nineteen", "Eighteen", "Seventeen", "Sixteen", "Fifteen", "Fourteen", "Thirteen", "Twelve", "Eleven", "Ten", "Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One"};

        if (num == 0) {
            return "Zero";
        }
        String rst = "";
        for (int i = 0; i < nums.length; i++) {
            if (num == nums[i]) {
                if (num < 100) {
                    return rst.length() == 0 ? strs[i] : rst + " " + strs[i];
                } else {
                    return rst.length() == 0 ? "One " + strs[i] : rst + " " + "One " + strs[i];
                }
            }
            int number = num / nums[i];           
            if (number > 0 && num >= 100) {
                rst = rst.length() == 0 ? numberToWords(number) + " " + strs[i] : rst + " " + numberToWords(number) + " " + strs[i];
            } else if (number > 0) {
                rst = rst.length() == 0 ? strs[i] : rst + " " + strs[i];
            }
            num = num % nums[i];
        }
        return rst;                             
    }
}

(2) Python



(3) Scala



results matching ""

    No results matching ""