KatInterview

273. Integer to English Words

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

The problem asks us to convert a non-negative integer into its English words representation. The numbers can be as large as $2^{31} - 1$. English number words have a clear structure based on groups of three digits. For instance, 1,234,567 is read as "One Million, Two Hundred Thirty Four Thousand, Five Hundred Sixty Seven". This suggests a strategy of breaking the number down into chunks of three digits and processing each chunk.

Solution

Integer to English Words in Python

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

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

        def helper(n: int) -> str:
            if n == 0:
                return ""
            if n < 20:
                return lessThan20[n]
            if n < 100:
                rem = helper(n % 10)
                return tens[n // 10] + (" " + rem if rem else "")
            # n >= 100
            rem = helper(n % 100)
            return lessThan20[n // 100] + " Hundred" + (" " + rem if rem else "")

        parts = []
        i = 0  # Index for thousands list

        while num > 0:
            if num % 1000 != 0:
                chunk_words = helper(num % 1000)
                if i > 0:
                    parts.append(thousands[i])
                parts.append(chunk_words)
            num //= 1000
            i += 1

        return " ".join(reversed(parts))

Integer to English Words in Java

import java.util.LinkedList;

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 = {
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
    };
    private final String[] thousands = {
        "", "Thousand", "Million", "Billion"
    };

    // Helper function to convert a number less than 1000 to words
    private String helper(int n) {
        if (n == 0) {
            return "";
        }
        if (n < 20) {
            return lessThan20[n];
        }
        if (n < 100) {
            String rem = helper(n % 10);
            return tens[n / 10] + (rem.isEmpty() ? "" : " " + rem);
        }
        // n >= 100
        String rem = helper(n % 100);
        return lessThan20[n / 100] + " Hundred" + (rem.isEmpty() ? "" : " " + rem);
    }

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

        LinkedList<String> parts = new LinkedList<>();
        int i = 0; // Index for thousands array

        while (num > 0) {
            if (num % 1000 != 0) {
                String chunkWords = helper(num % 1000);
                if (i > 0) {
                    parts.addFirst(thousands[i]);
                }
                parts.addFirst(chunkWords);
            }
            num /= 1000;
            i++;
        }

        return String.join(" ", parts);
    }
}

Integer to English Words in C++

class Solution {
private:
    const vector<string> lessThan20 = {
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
        "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
    const vector<string> tens = {
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
    };
    const vector<string> thousands = {
        "", "Thousand", "Million", "Billion"
    };

    // Helper function to convert a number less than 1000 to words
    string helper(int n) {
        if (n == 0) {
            return "";
        }
        if (n < 20) {
            return lessThan20[n];
        } 
        if (n < 100) {
            string rem = helper(n % 10);
            return tens[n / 10] + (rem.empty() ? "" : " " + rem);
        }
        // n >= 100
        string rem = helper(n % 100);
        return lessThan20[n / 100] + " Hundred" + (rem.empty() ? "" : " " + rem);
    }

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

        vector<string> parts;
        int i = 0; // Index for thousands array

        while (num > 0) {
            if (num % 1000 != 0) {
                string chunk_words = helper(num % 1000);
                if (i > 0) {
                    chunk_words += " " + thousands[i];
                }
                parts.push_back(chunk_words);
            }
            num /= 1000;
            i++;
        }

        // Reverse the parts and join them with spaces
        reverse(parts.begin(), parts.end());
        string result;
        for (size_t j = 0; j < parts.size(); ++j) {
            result += parts[j];
            if (j < parts.size() - 1) {
                result += " ";
            }
        }

        return result;
    }
};

Integer to English Words in TypeScript

function numberToWords(num: number): string {
    if (num === 0) {
        return "Zero";
    }

    const lessThan20: string[] = [
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
        "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    ];
    const tens: string[] = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
    const thousands: string[] = ["", "Thousand", "Million", "Billion"];

    // Helper function to convert a number less than 1000 to words
    const helper = (n: number): string => {
        if (n === 0) {
            return "";
        }
        if (n < 20) {
            return lessThan20[n];
        }
        if (n < 100) {
            const rem = helper(n % 10);
            return tens[Math.floor(n / 10)] + (rem ? ` ${rem}` : "");
        }
        // n >= 100
        const rem = helper(n % 100);
        return lessThan20[Math.floor(n / 100)] + " Hundred" + (rem ? ` ${rem}` : "");
    };

    const parts: string[] = [];
    let i = 0; // Index for thousands array

    while (num > 0) {
        if (num % 1000 !== 0) {
            const chunkWords = helper(num % 1000);
            if (i > 0) {
                parts.unshift(thousands[i]);
            }
            parts.unshift(chunkWords);
        }
        num = Math.floor(num / 1000);
        i++;
    }

    return parts.join(" ");
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.