Integer to English Words

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"

Analysis

  • Helper function takes number less than 1000 and return words

  • Main function

    • index = 0
    • While num!=0
      • Add thousands[index] to the front of answer
      • Get the last 3 digits (num%1000), use helper function convert to words, add to the front of answer
      • num /= 1000
      • index++

Code

public class Solution {
    private final String[] lessThan20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private final String[] thousands = {"", "Thousand", "Million", "Billion"};

    public String numberToWords(int num) {
        if (num==0) return "zero";
        String ans = "";
        int index = 0;

        while (num!=0){
            if (num%1000!=0){
                ans = helper(num%1000)+ " "+ thousands[index] + " " + ans;
            }
            num /= 1000;
            index++;
        }

        return ans.trim();
    }

    //helper function takes in number less than 1000 and return words
    private String helper(int num){
        assert(num<1000);
        if (num==0) {return "";}
        else if (num<20){
            return lessThan20[num].trim();
        }
        else if (num<100){
            return (tens[num / 10] + " " + helper(num % 10)).trim();
        }
        else {
            return (lessThan20[num / 100] + " Hundred " + helper(num % 100)).trim();
        }
    }
}

Note

  • 空格的处理
  • string.trim(): omit leading and trailing spaces

Reference

Leetcode