Question

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

  • Method 1:
    class Solution {
        private static String[] bigUnit = new String[]{"", "Thousand", "Million", "Billion"};
        private static String[] numbers = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
        private static String[] tens = new String[]{"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        private static String[] overTens = new String[]{"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        public String numberToWords(int num) {
            if(num == 0) return "Zero";
            String result = "";
            int bigUnitIndex = 0;
            while(num > 0){
                String temp = parseThree(num % 1000);
                if(temp.length() != 0){
                    result = temp
                    + (bigUnitIndex == 0 ? "": " ")
                    + bigUnit[bigUnitIndex]
                    + (result.length() == 0 ? "": " ") + result;
                }
                bigUnitIndex++;
                num /= 1000;
            }
            return result;
        }
        private String parseThree(int num){
            String res = "";
            if(num % 100 > 10 && num % 100 < 20){
                res = overTens[num % 100 - 10];
                num /= 100;
            }else{
                if(num % 10 != 0){
                    res = numbers[num % 10];
                }
                num /= 10;
                if(num % 10 != 0){
                    res = tens[num % 10] + (res.length() == 0 ? "":" ") + res;
                }
                num /= 10;
            }
            if(num % 10 != 0){
                res = numbers[num % 10] + " Hundred" + (res.length() == 0 ? "": " ") + res;
            }
            return res;
        }
    }