Integer to English Words

Updated on 06 June, 2025
Integer to English Words header image

Problem Statement

The task requires developing a method to convert a non-negative integer, referred to as num, into its corresponding English words representation. For example, the number 123 should be transformed into the string "One Hundred Twenty Three". The algorithm must handle a range of numbers from 0 up to 2^31 - 1, which covers a diverse set of possible integers including single digits, tens, hundreds, thousands, and up into the millions and billions.

Examples

Example 1

Input:

num = 123

Output:

"One Hundred Twenty Three"

Example 2

Input:

num = 12345

Output:

"Twelve Thousand Three Hundred Forty Five"

Example 3

Input:

num = 1234567

Output:

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

Constraints

  • 0 <= num <= 231 - 1

Approach and Intuition

Converting a number into its English word equivalent involves understanding and implementing a few linguistic rules and patterns. From the examples provided, we can extract a clear need for a structured approach to breaking down the numbers into manageable parts (like hundreds, thousands, millions) and then converting these parts into words.

  1. Break Down the Problem: Decompose the number into units, tens, hundreds, and so forth. For example, for the number 1234567, we can separate it into millions (1), thousands (234), and the rest (567).
  2. Mapping Digits to Words: Use a dictionary or similar data structure to map individual digits and specific two-digit numbers (like 11-19 and multiples of ten up to ninety) to their word equivalents.
  3. Recursive or Iterative Conversion: For each segmented part of the number, convert it using recursion or iteration. This involves converting the highest significant digit first, followed by the next, appending the right scale (like thousand or million) as you move along.
  4. Edge Cases: Ensure that zeros in numbers don't add unnecessary words ("zero hundred" should not appear).
  5. Formatting Results: After converting, format the string appropriately to ensure all words are properly concatenated with spaces, and no redundant spaces are included.

By applying these steps, we can reliably convert any integer within the given constraints into its English words representation, as shown in the examples.

Solutions

  • C++
  • Java
  • Python
cpp
class Translator {
public:
    vector<pair<int, string>> numToEng = {
        {1000000000, "Billion"}, {1000000, "Million"}, {1000, "Thousand"},
        {100, "Hundred"}, {90, "Ninety"}, {80, "Eighty"}, {70, "Seventy"},
        {60, "Sixty"}, {50, "Fifty"}, {40, "Forty"}, {30, "Thirty"},
        {20, "Twenty"}, {19, "Nineteen"}, {18, "Eighteen"}, {17, "Seventeen"},
        {16, "Sixteen"}, {15, "Fifteen"}, {14, "Fourteen"}, {13, "Thirteen"},
        {12, "Twelve"}, {11, "Eleven"}, {10, "Ten"}, {9, "Nine"}, {8, "Eight"},
        {7, "Seven"}, {6, "Six"}, {5, "Five"}, {4, "Four"}, {3, "Three"},
        {2, "Two"}, {1, "One"}
    };

    string integerToEnglish(int value) {
        if (value == 0) {
            return "Zero";
        }

        for (auto& [num, text] : numToEng) {
            if (value >= num) {
                string head = (value >= 100) ? integerToEnglish(value / num) + " " : "";
                string middle = text;
                string tail = (value % num == 0) ? "" : " " + integerToEnglish(value % num);

                return head + middle + tail;
            }
        }

        return "";
    }
};

Translate an integer into its English words representation using C++. The solution employs a class named Translator that includes a method integerToEnglish. Here's how you can understand and utilize this solution:

  • The Translator class possesses a vector of pair<int, string> named numToEng, which stores numbers and their corresponding English words from highest (Billion) to lowest (One). This helps map significant numerical values to their respective word forms.

  • The integerToEnglish method takes an integer value as input and returns its English words representation. If the input value is zero, the function directly returns the string "Zero".

  • Utilize a loop to iterate through the numToEng vector. Check each number to see if the input value is greater than or equal to the number in the pair.

  • Construct the string in three components:

    • head: If the number is greater than or equal to 100, recursively calculate the English representation for the quotient of the division of value by num. Add a space after this part.
    • middle: The word representation of the current number from the vector.
    • tail: If there is a remainder from the division (value % num), recursively call integerToEnglish with this remainder and prepend a space.
  • Combine the head, middle, and tail to form the full English phrase for the given number. This helps in recursively breaking down the number into manageable parts which can then be converted into their word equivalents.

  • Return the concatenated string which provides the full English representation of the integer.

This methodology ensures accurate translation of an integer to its English words equivalent by recursively segmenting the number according to its size (Billion, Million, etc.), which simplifies understanding and constructing the number in natural language.

java
class IntWord {
    int num;
    String label;

    IntWord(int num, String label) {
        this.num = num;
        this.label = label;
    }
}

class NumberConverter {
    private static final List<IntWord> numLabelList = Arrays.asList(
        new IntWord(1000000000, "Billion"), new IntWord(1000000, "Million"),
        new IntWord(1000, "Thousand"), new IntWord(100, "Hundred"),
        new IntWord(90, "Ninety"), new IntWord(80, "Eighty"),
        new IntWord(70, "Seventy"), new IntWord(60, "Sixty"),
        new IntWord(50, "Fifty"), new IntWord(40, "Forty"),
        new IntWord(30, "Thirty"), new IntWord(20, "Twenty"),
        new IntWord(19, "Nineteen"), new IntWord(18, "Eighteen"),
        new IntWord(17, "Seventeen"), new IntWord(16, "Sixteen"),
        new IntWord(15, "Fifteen"), new IntWord(14, "Fourteen"),
        new IntWord(13, "Thirteen"), new IntWord(12, "Twelve"),
        new IntWord(11, "Eleven"), new IntWord(10, "Ten"),
        new IntWord(9, "Nine"), new IntWord(8, "Eight"),
        new IntWord(7, "Seven"), new IntWord(6, "Six"),
        new IntWord(5, "Five"), new IntWord(4, "Four"),
        new IntWord(3, "Three"), new IntWord(2, "Two"),
        new IntWord(1, "One")
    );

    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }

        for (IntWord iw : numLabelList) {
            if (num >= iw.num) {
                String prefix = (num >= 100) ? numberToWords(num / iw.num) + " " : "";
                String unit = iw.label;
                String suffix = (num % iw.num == 0) ? "" : " " + numberToWords(num % iw.num);

                return prefix + unit + suffix;
            }
        }

        return "";
    }
}

The provided Java code defines a class IntWord for associating integer numbers with their English word equivalents. Another class, NumberConverter, includes a method numberToWords which converts any integer into its English word representation. The method uses a list of IntWord objects that map significant numbers like 1, 2, 10, 100, 1000, and so forth up to a billion to their corresponding English words.

Follow these steps to understand the code logic:

  1. Check if the input number is zero; if yes, return the string "Zero".
  2. Iterate through the list of IntWord objects. For each object, check if the input number is greater than or equal to the object's number value.
  3. If it is, compute and concatenate the English word equivalents by geographically dividing the number by the object's number value (for the prefix), obtaining the word from IntWord (for the unit), and getting the remainder of the division operation recursively converted into words (for the suffix).
  4. The function forms a complete sentence by combining these components (prefix, unit, suffix), ensuring no extra spaces or ungrammatical sequences appear.

This approach breaks down the input number into manageable segments, each corresponding to a part of the English language expression of the number, effectively transforming numerical values into their linguistic expressions by recursive processing in combination with direct mappings.

Review this code if you need to convert large numbers into words for applications like cheque-writing systems, legal documentation, or any software that requires natural language processing of numeric data. The methodology ensures accuracy, scalability, and ease of maintenance by using clear mappings and simple recursive decomposition.

python
class NumberConverter:
    # Map of numbers to their respective words
    num_to_word = {
        1000000000: "Billion", 1000000: "Million", 1000: "Thousand",
        100: "Hundred", 90: "Ninety", 80: "Eighty", 70: "Seventy",
        60: "Sixty", 50: "Fifty", 40: "Forty", 30: "Thirty",
        20: "Twenty", 19: "Nineteen", 18: "Eighteen", 17: "Seventeen",
        16: "Sixteen", 15: "Fifteen", 14: "Fourteen", 13: "Thirteen",
        12: "Twelve", 11: "Eleven", 10: "Ten", 9: "Nine", 8: "Eight",
        7: "Seven", 6: "Six", 5: "Five", 4: "Four", 3: "Three",
        2: "Two", 1: "One"
    }

    def convertToWords(self, num: int) -> str:
        if num == 0:
            return "Zero"

        for key, value in self.num_to_word.items():
            if num >= key:
                lead = (self.convertToWords(num // key) + " ") if num >= 100 else ""
                unit = value
                tail = "" if num % key == 0 else " " + self.convertToWords(num % key)

                return lead + unit + tail

        return ""

This solution translates a given integer into its corresponding English words using Python. The approach employs recursion and a dictionary for efficient mapping of numbers to their respective word equivalents.

Solution Overview:

  • The NumberConverter class contains a dictionary num_to_word where integers map to their word forms. The mapping covers bases from individual numbers (1 to 19), tens (20, 30, ... 90), and higher denominators like 'Hundred', 'Thousand', up to 'Billion'.
  • The convertToWords function performs the core conversion:
    • Check for zero case directly, returning the word "Zero".
    • Loop through the dictionary items in descending numerical order:
      • Calculate leading words if the number is greater than or equal to the base (100). This involves a recursive call to process the quotient of the division of num by key.
      • Attach the appropriate scale (like "Thousand" or "Million") based on the current dictionary value.
      • For non-exact multiples, recursively process the remainder of num divided by key.
      • Return the concatenated result as the English word representation of the number.

Key Details:

  • Recursion handles both partitoning the number into manageable sections (based on size like hundreds, thousands, etc.) and dealing with non-unit quotas (like processing the number 22 as "Twenty Two").
  • This methodology efficiently breaks down the number and systematically translates it, leveraging the predefined dictionary for straightforward lookup and concatenation tasks.

This system is highly effective for converting integers into their English word equivalents, making it useful in applications where numeric values need to be presented in written form.

Comments

No comments yet.