HomeLeetcode273. Integer to English Words - Leetcode Solutions

273. Integer to English Words – Leetcode Solutions

Description

Convert a non-negative integer num to its English words representation.

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"

Solution in Python

Python
class Solution:
    def numberToWords(self, num: int) -> str:
        # Helper arrays for under twenty and tens names
        below_20 = ['Zero', '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']
        
        # Big units like thousand, million, billion
        thousands = ['', 'Thousand', 'Million', 'Billion']
        
        # Edge case for zero
        if num == 0:
            return 'Zero'

        def helper(n: int) -> str:
            # If the number is less than 20, we return it directly from below_20 array
            if n < 20:
                return below_20[n]
            # For numbers between 20 and 99, we return the tens place and if there is a remainder,
            # we append the word from below_20
            elif n < 100:
                return tens[n // 10] + ('' if n % 10 == 0 else ' ' + below_20[n % 10])
            # For numbers between 100 and 999, we recursively call the helper function for 
            # hundreds place and remainder
            else:
                return below_20[n // 100] + ' Hundred' + ('' if n % 100 == 0 else ' ' + helper(n % 100))

        # Main part of the function
        res = ''
        for i, unit in enumerate(thousands):
            # Extract the last three digits
            if num % 1000 != 0:
                res = helper(num % 1000) + (' ' + unit if unit else '') + (' ' + res if res else '')
            num //= 1000
            if num == 0:
                break

        return res.strip()  # Remove any leading or trailing spaces

Explanation:

  1. Arrays for words:
    • below_20: Stores the word representation for numbers less than 20.
    • tens: Stores word representation for multiples of ten (from 20 to 90).
    • thousands: Contains the big units (like ‘Thousand’, ‘Million’, etc.).
  2. Edge case for zero:
    • If the input is zero, we return ‘Zero’ directly since this is a special case.
  3. Helper function helper:
    • Converts numbers below 1000 to words.
    • For numbers less than 20, we use below_20.
    • For numbers between 20 and 99, we use tens and add the remainder if any.
    • For numbers between 100 and 999, we divide the number by 100 to get the hundreds place and recursively convert the remainder.
  4. Main function logic:
    • We loop through the number, extracting three digits at a time (from the right).
    • For each set of three digits, we convert them to words using the helper function and add the appropriate big unit (Thousand, Million, etc.).
    • The result is built by appending the words for each block of three digits.
    • Once all digits are processed, we return the final result after stripping any extra spaces.

This approach effectively handles all numbers within the given constraint (0 ≤ num ≤ 2^31 – 1).

Solution in C++

C++
class Solution {
public:
    // Function to convert a number to words
    string numberToWords(int num) {
        // Arrays storing English words for numbers less than 20 and multiples of ten
        vector<string> below_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
                                   "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", 
                                   "Eighteen", "Nineteen"};
        
        vector<string> tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        
        // Array storing the big units
        vector<string> thousands = {"", "Thousand", "Million", "Billion"};
        
        // Edge case for 0
        if (num == 0) {
            return "Zero";
        }
        
        // The result string
        string result = "";
        
        // Iterate over the number in chunks of 1000, converting each part to words
        for (int i = 0; num > 0; ++i) {
            if (num % 1000 != 0) {
                // Convert the last three digits to words and prepend them to the result string
                string chunk = helper(num % 1000, below_20, tens);
                if (!chunk.empty()) {
                    result = chunk + (thousands[i].empty() ? "" : " " + thousands[i]) + (result.empty() ? "" : " " + result);
                }
            }
            num /= 1000;  // Move on to the next three digits
        }
        
        // Return the final result without trailing or leading spaces
        return result;
    }

private:
    // A helper function to convert numbers less than 1000 into words
    string helper(int n, vector<string>& below_20, vector<string>& tens) {
        if (n == 0) return "";  // If number is zero, return an empty string
            
        if (n < 20) {
            // Numbers less than 20 can be directly mapped from the below_20 array
            return below_20[n];
        } else if (n < 100) {
            // For numbers between 20 and 99, map the tens part, and recursively call helper for the ones place
            return tens[n / 10] + (n % 10 == 0 ? "" : " " + below_20[n % 10]);
        } else {
            // For numbers between 100 and 999, map the hundreds place and recursively call helper for the rest
            return below_20[n / 100] + " Hundred" + (n % 100 == 0 ? "" : " " + helper(n % 100, below_20, tens));
        }
    }
};

Solution in Javascript

JavaScript
var numberToWords = function(num) {
    // Arrays for numbers below 20 and tens
    const below_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", 
                      "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", 
                      "Seventeen", "Eighteen", "Nineteen"];
    
    const tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
    
    // Array to hold the big units
    const thousands = ["", "Thousand", "Million", "Billion"];
    
    // Edge case for 0
    if (num === 0) {
        return "Zero";
    }
    
    // Function to convert numbers less than 1000 to words
    const helper = (n) => {
        if (n === 0) return ""; // If number is zero, return empty string
        
        if (n < 20) {
            return below_20[n]; // Direct mapping for numbers less than 20
        } else if (n < 100) {
            return tens[Math.floor(n / 10)] + (n % 10 === 0 ? "" : " " + below_20[n % 10]); // Tens and units
        } else {
            return below_20[Math.floor(n / 100)] + " Hundred" + (n % 100 === 0 ? "" : " " + helper(n % 100)); // Hundreds
        }
    };
    
    // The result string
    let result = "";
    
    // Iterate over the number in chunks of 1000
    for (let i = 0; num > 0; i++) {
        if (num % 1000 !== 0) {
            // Convert the last three digits to words and prepend to result
            const chunk = helper(num % 1000); // Convert chunk to words
            result = chunk + (thousands[i] ? " " + thousands[i] : "") + (result ? " " + result : "");
        }
        num = Math.floor(num / 1000); // Move to the next three digits
    }
    
    return result.trim(); // Return the final result, trimmed of any leading or trailing spaces
};

Solution in Java

Java
class Solution {
    public String numberToWords(int num) {
        // Arrays for numbers below 20 and multiples of ten
        String[] below_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
                              "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
                              "Seventeen", "Eighteen", "Nineteen"};
        
        String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        
        // Array to hold the big units
        String[] thousands = {"", "Thousand", "Million", "Billion"};
        
        // Edge case for 0
        if (num == 0) {
            return "Zero";
        }
        
        // The result string
        StringBuilder result = new StringBuilder();
        
        // Iterate over the number in chunks of 1000
        for (int i = 0; num > 0; i++) {
            // Process the last three digits
            if (num % 1000 != 0) {
                // Convert the last three digits to words
                String chunk = helper(num % 1000, below_20, tens);
                // Append the chunk and the corresponding big unit
                result.insert(0, chunk + (thousands[i].isEmpty() ? "" : " " + thousands[i]) + (result.length() == 0 ? "" : " "));
            }
            num /= 1000; // Move to the next three digits
        }
        
        return result.toString().trim(); // Return the final result, trimmed of any leading or trailing spaces
    }

    // Helper function to convert numbers less than 1000 into words
    private String helper(int n, String[] below_20, String[] tens) {
        if (n == 0) return ""; // If number is zero, return empty string
        
        if (n < 20) {
            return below_20[n]; // Direct mapping for numbers less than 20
        } else if (n < 100) {
            return tens[n / 10] + (n % 10 == 0 ? "" : " " + below_20[n % 10]); // Tens and units
        } else {
            return below_20[n / 100] + " Hundred" + (n % 100 == 0 ? "" : " " + helper(n % 100, below_20, tens)); // Hundreds
        }
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular