Program to convert a given number to words (original) (raw)

Last Updated : 12 Nov, 2024

Given a non-negative integer n, the task is to convert the given number into its English representation according to International Number System.

**Examples:

**Input: n = 0
**Output: "Zero"

**Input: n = 123
****Output: "**One Hundred Twenty Three"

**Input: n = 10245
Output: "Ten Thousand Two Hundred Forty Five"

**Input: n = 2147483647
**Output: "Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven"

Table of Content

[Approach 1] By breaking down the number into groups of three digits

The idea is to divide the number into **groups of three digits (Thousands, Millions, Billions) and process each group separately. For each group, we convert the digits in the **Hundreds, **Tens, and **Units places into their corresponding words, then, append the corresponding **multiplier (like Thousand, Million, Billion). This process continues until the entire number is traversed. Finally, we combine all the groups, which form the complete English representation of the given number.

C++ `

// C++ program to convert number into words by breaking // it into groups of three

#include #include #include using namespace std;

string convertToWords(int n) { if (n == 0) return "Zero";

// Words for numbers 0 to 19
vector<string> units = {
    "",        "One",       "Two",      "Three",
    "Four",    "Five",      "Six",      "Seven",
    "Eight",   "Nine",      "Ten",      "Eleven",
    "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
    "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};

// Words for numbers multiple of 10        
vector<string> tens = { 
    "",     "",     "Twenty",  "Thirty", "Forty",
    "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" 
};

vector<string> multiplier = 
                {"", "Thousand", "Million", "Billion"};

string res = "";
int group = 0;

// Process number in group of 1000s
while (n > 0) {
    if (n % 1000 != 0) {
        
        int value = n % 1000;
        string temp = "";
        
        // Handle 3 digit number
        if (value >= 100) {
            temp = units[value / 100] + " Hundred ";
            value %= 100;
        }

        // Handle 2 digit number
        if (value >= 20) {
            temp += tens[value / 10] + " ";
            value %= 10;
        }

        // Handle unit number
        if (value > 0) {
            temp += units[value] + " ";
        }

        // Add the multiplier according to the group
        temp += multiplier[group] + " ";
        
        // Add this group result to overall result
        res = temp + res;
    }
    n /= 1000;
    group++;
}

// Remove trailing space
return res.substr(0, res.find_last_not_of(" ") + 1);

}

int main() { int n = 2147483647; cout << convertToWords(n) << endl; return 0; }

Java

// Java program to convert number into words by breaking // it into groups of three

import java.util.*;

class GfG { static String convertToWords(int n) { if (n == 0) return "Zero";

    // Words for numbers 0 to 19
    String[] units = {
        "",        "One",       "Two",      "Three",
        "Four",    "Five",      "Six",      "Seven",
        "Eight",   "Nine",      "Ten",      "Eleven",
        "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
    
    // Words for numbers multiple of 10        
    String[] tens = { 
        "",     "",     "Twenty",  "Thirty", "Forty",
        "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" 
    };
    
    String[] multiplier = 
                {"", "Thousand", "Million", "Billion"};
  
    String res = "";
    int group = 0;
    
    // Process number in group of 1000s
    while (n > 0) {
        if (n % 1000 != 0) {
            
            int value = n % 1000;
            String temp = "";
            
            // Handle 3 digit number
            if (value >= 100) {
                temp = units[value / 100] + " Hundred ";
                value %= 100;
            }

            // Handle 2 digit number
            if (value >= 20) {
                temp += tens[value / 10] + " ";
                value %= 10;
            }

            // Handle unit number
            if (value > 0) {
                temp += units[value] + " ";
            }

            // Add the multiplier according to the group
            temp += multiplier[group] + " ";
            
            // Add this group result to overall result
            res = temp + res;
        }
        n /= 1000;
        group++;
    }
    
    // Remove trailing space
    return res.trim();
}

public static void main(String[] args) {
    int n = 2147483647;
    System.out.println(convertToWords(n));
}

}

Python

Python program to convert number into words by breaking

it into groups of three

def convertToWords(n): if n == 0: return "Zero"

# Words for numbers 0 to 19
units = [
    "",        "One",       "Two",      "Three",
    "Four",    "Five",      "Six",      "Seven",
    "Eight",   "Nine",      "Ten",      "Eleven",
    "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
    "Sixteen", "Seventeen", "Eighteen", "Nineteen"
]

# Words for numbers multiple of 10        
tens = [
    "",     "",     "Twenty",  "Thirty", "Forty",
    "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
]

multiplier = ["", "Thousand", "Million", "Billion"]

res = ""
group = 0

# Process number in group of 1000s
while n > 0:
    if n % 1000 != 0:
        
        value = n % 1000
        temp = ""
        
        # Handle 3 digit number
        if value >= 100:
            temp = units[value // 100] + " Hundred "
            value %= 100

        # Handle 2 digit number
        if value >= 20:
            temp += tens[value // 10] + " "
            value %= 10

        # Handle unit number
        if value > 0:
            temp += units[value] + " "

        # Add the multiplier according to the group
        temp += multiplier[group] + " "
        
        # Add the result of this group to overall result
        res = temp + res
    n //= 1000
    group += 1

# Remove trailing space
return res.strip()

if name == "main": n = 2147483647 print(convertToWords(n))

C#

// C# program to convert number into words by breaking // it into groups of three

using System; using System.Collections.Generic;

class GfG { static string ConvertToWords(int n) { if (n == 0) return "Zero";

    // Words for numbers 0 to 19
    string[] units = {
        "",        "One",       "Two",      "Three",
        "Four",    "Five",      "Six",      "Seven",
        "Eight",   "Nine",      "Ten",      "Eleven",
        "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };
    
    // Words for numbers multiple of 10        
    string[] tens = { 
        "",     "",     "Twenty",  "Thirty", "Forty",
        "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" 
    };
    
    string[] multiplier = 
                {"", "Thousand", "Million", "Billion"};
  
    string res = "";
    int group = 0;
    
    // Process number in group of 1000s
    while (n > 0) {
        if (n % 1000 != 0) {
            
            int value = n % 1000;
            string temp = "";
            
            // Handle 3 digit number
            if (value >= 100) {
                temp = units[value / 100] + " Hundred ";
                value %= 100;
            }

            // Handle 2 digit number
            if (value >= 20) {
                temp += tens[value / 10] + " ";
                value %= 10;
            }

            // Handle unit number
            if (value > 0) {
                temp += units[value] + " ";
            }

            // Add the multiplier according to the group
            temp += multiplier[group] + " ";
            
            // Add the this group result to overall result
            res = temp + res;
        }
        n /= 1000;
        group++;
    }
    
    // Remove trailing space
    return res.Trim();
}

static void Main() {
    int n = 2147483647;
    Console.WriteLine(ConvertToWords(n));
}

}

JavaScript

// JavaScript program to convert number into words by breaking // it into groups of three

function convertToWords(n) { if (n === 0) return "Zero";

// Words for numbers 0 to 19
const units = [
    "",        "One",       "Two",      "Three",
    "Four",    "Five",      "Six",      "Seven",
    "Eight",   "Nine",      "Ten",      "Eleven",
    "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
    "Sixteen", "Seventeen", "Eighteen", "Nineteen"
];

// Words for numbers multiple of 10        
const tens = [
    "",     "",     "Twenty",  "Thirty", "Forty",
    "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
];

const multiplier = ["", "Thousand", "Million", "Billion"];

let res = "";
let group = 0;

// Process number in group of 1000s
while (n > 0) {
    if (n % 1000 !== 0) {
        
        let value = n % 1000;
        let temp = "";
        
        // Handle 3 digit number
        if (value >= 100) {
            temp = units[Math.floor(value / 100)] + " Hundred ";
            value %= 100;
        }

        // Handle 2 digit number
        if (value >= 20) {
            temp += tens[Math.floor(value / 10)] + " ";
            value %= 10;
        }

        // Handle unit number
        if (value > 0) {
            temp += units[value] + " ";
        }

        // Add the multiplier according to the group
        temp += multiplier[group] + " ";
        
        // Add the result of this group to overall result
        res = temp + res;
    }
    n = Math.floor(n / 1000);
    group++;
}

// Remove trailing space
return res.trim();

}

const n = 2147483647; console.log(convertToWords(n));

`

Output

Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven

**Time Complexity: O(log10(n)) - As we are dividing the number by a multiple of ten (like 1000, 100, 10), reducing the number logarithmically.
**Auxiliary Space: O(1)

[Approach 2] By Mapping Key Numeric Values with English Words

_The idea is to **store _the key numeric values, such as billion, million, thousand, hundred, tens, and units and their corresponding English words in **descending _order. We compare the given number with these values, starting from the **largest . If the number is **greater _than or equal to the current numeric value, we first add the word for the **quotient (number / numeric value) , then append the word for the **current numeric value (like "Billion", "Thousand", or "Hundred"), and finally append the word for the remainder ****(number % numeric value)** _recursively. This process continues until the entire number is converted to words.

For example, if the number is 203. So, the first key numeric value which is smaller than this number is 100.

  1. First, we add the quotient part = 203 / 100 = 2, result = "Two".
  2. Next, we append the word for key numeric value which is 100, result = "Two Hundred" .
  3. Finally, we append the word for remainder part = 203 % 100 = 3, so the final result is = "Two Hundred Three". C++ `

// C++ program to convert number into words by Mapping Key Numeric Values // with English Words

#include #include #include using namespace std;

string convertToWordsRec(int n, vector &values, vector &words) { string res = "";

// Iterating over all key Numeric values
for (int i = 0; i < values.size(); i++) {
    int value = values[i];
    string word = words[i];

    // If the number is greater than or 
    // equal to the current numeric value
    if (n >= value) {

        // Append the quotient part
        // If the number is greater than or equal to 100
        // then only we need to handle that
        if (n >= 100)
            res += convertToWordsRec(n / value, values, words) + " ";

        // Append the word for numeric value
        res += word;

        // Append the remainder part
        if (n % value > 0)
            res += " " + convertToWordsRec(n % value, values, words);

        return res;
    }
}

return res;

}

string convertToWords(int n) { if (n == 0) return "Zero";

// Key Numeric values and their corresponding English words
vector<int> values = {1000000000, 1000000, 1000, 100, 90, 80, 70, 
                      60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
                      13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

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

return convertToWordsRec(n, values, words);

}

int main() { int n = 2147483647; cout << convertToWords(n) << endl; return 0; }

Java

// Java program to convert number into words by Mapping Key Numeric // Values with English Words

class GfG {

// Method to convert number into words recursively
static String convertToWordsRec(int n, int[] values, String[] words) {
    String res = "";

    // Iterating over all key Numeric values
    for (int i = 0; i < values.length; i++) {
        int value = values[i];
        String word = words[i];

        // If the number is greater than or equal to current numeric value
        if (n >= value) {

            // Append the quotient part
            // If the number is greater than or equal to 100
            // then only we need to handle that
            if (n >= 100)
                res += convertToWordsRec(n / value, values, words) + " ";

            // Append the word for numeric value
            res += word;

            // Append the remainder part
            if (n % value > 0)
                res += " " + convertToWordsRec(n % value, values, words);

            return res;
        }
    }

    return res;
}

static String convertToWords(int n) {
    if (n == 0)
        return "Zero";

    // Key Numeric values and their corresponding English words
    int[] values = {
        1000000000, 1000000, 1000, 100, 90, 80, 70,
        60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
        13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
    };

    String[] words = {
        "Billion", "Million", "Thousand", "Hundred",
        "Ninety", "Eighty", "Seventy", "Sixty", "Fifty",
        "Forty", "Thirty", "Twenty", "Nineteen",
        "Eighteen", "Seventeen", "Sixteen", "Fifteen",
        "Fourteen", "Thirteen", "Twelve", "Eleven",
        "Ten", "Nine", "Eight", "Seven", "Six", "Five",
        "Four", "Three", "Two", "One"
    };

    return convertToWordsRec(n, values, words);
}

public static void main(String[] args) {
    int n = 2147483647;
    System.out.println(convertToWords(n));
}

}

Python

Python program to convert number into words by Mapping Key Numeric Values

with English Words

def convertToWordsRec(n, values, words): res = ""

# Iterating over all key Numeric values
for i in range(len(values)):
    value = values[i]
    word = words[i]

    # If the number is greater than or equal to the current numeric value
    if n >= value:

        # Append the quotient part
        # If the number is greater than or equal to 100
        # then only we need to handle that
        if n >= 100:
            res += convertToWordsRec(n // value, values, words) + " "

        # Append the word for numeric value
        res += word

        # Append the remainder part
        if n % value > 0:
            res += " " + convertToWordsRec(n % value, values, words)

        return res

return res

def convertToWords(n): if n == 0: return "Zero"

# Key Numeric values and their corresponding English words
values = [1000000000, 1000000, 1000, 100, 90, 80, 70, 
          60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
          13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

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

return convertToWordsRec(n, values, words)

if name == "main": n = 2147483647 print(convertToWords(n))

C#

// C# program to convert number into words by Mapping Key Numeric Values // with English Words

using System;

class GfG { static string convertToWordsRec(int n, int[] values, string[] words) { string res = "";

    // Iterating over all key Numeric values
    for (int i = 0; i < values.Length; i++) {
        int value = values[i];
        string word = words[i];

        // If the number is greater than or equal to the current numeric value
        if (n >= value) {

            // Append the quotient part
            // If the number is greater than or equal to 100
            // then only we need to handle that
            if (n >= 100)
                res += convertToWordsRec(n / value, values, words) + " ";

            // Append the word for numeric value
            res += word;

            // Append the remainder part
            if (n % value > 0)
                res += " " + convertToWordsRec(n % value, values, words);

            return res;
        }
    }

    return res;
}

static string convertToWords(int n) {
    if (n == 0)
        return "Zero";

    // Key Numeric values and their corresponding English words
    int[] values = {
        1000000000, 1000000, 1000, 100, 90, 80, 70, 
        60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
        13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
    };

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

    return convertToWordsRec(n, values, words);
}

static void Main() {
    int n = 2147483647;
    Console.WriteLine(convertToWords(n));
}

}

JavaScript

// JavaScript program to convert number into words by Mapping Key Numeric Values // with English Words

function convertToWordsRec(n, values, words) { let res = "";

// Iterating over all key Numeric values
for (let i = 0; i < values.length; i++) {
    let value = values[i];
    let word = words[i];

    // If the number is greater than or equal to the current numeric value
    if (n >= value) {

        // Append the quotient part
        // If the number is greater than or equal to 100
        // then only we need to handle that
        if (n >= 100)
            res += convertToWordsRec(Math.floor(n / value), values, words) + " ";

        // Append the word for numeric value
        res += word;

        // Append the remainder part
        if (n % value > 0)
            res += " " + convertToWordsRec(n % value, values, words);

        return res;
    }
}

return res;

}

function convertToWords(n) { if (n === 0) return "Zero";

// Key Numeric values and their corresponding English words
const values = [1000000000, 1000000, 1000, 100, 90, 80, 70, 
                60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14,
                13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];

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

return convertToWordsRec(n, values, words);

}

let n = 2147483647; console.log(convertToWords(n));

`

Output

Two Billion One Hundred Forty Seven Million Four Hundred Eighty Three Thousand Six Hundred Forty Seven

**Time Complexity: O(log10(n)) - As we are dividing the number by a key numeric value (typically by 1000, 100, etc.), reducing the number logarithmically with each call.
**Auxiliary Space: O(log10(n)) - Recursion stack size will be same as the total number of recursive calls.