In many applications, converting a given number into its word equivalent can be quite useful. Whether it’s for a financial report, a software interface, or even for educational purposes, being able to convert a numeric value into readable words is a common task.
For example, converting the number 1234
should output “one thousand two hundred thirty-four”.
In this article, we will discuss how to write an algorithm that can convert any given integer into words.
Given a number like 9923
, the task is to convert it to its word equivalent, which would be “nine thousand nine hundred twenty-three”.
To solve this problem, we’ll break the number into segments (thousands, hundreds, tens, and units) and use predefined mappings for each segment. We will convert each part into words and then combine them to form the final output.
Here’s how we can implement this in Python:
ones
: This contains the words for numbers 0-19.tens
: This contains the words for multiples of ten, like twenty, thirty, etc.thousands
: This is used for large numbers (thousand, million, etc.).helper
function handles numbers less than 1000. It processes numbers by breaking them into hundreds, tens, and ones:ones
array.helper
function and appends the corresponding thousand, million, etc., label.strip()
method ensures that extra spaces at the ends are removed before returning the final string.The time complexity of this solution is O(n)O(n), where nn is the number of digits in the given number. Each chunk of the number is processed in constant time, and we process a maximum of three digits at a time.
Input:9923
Output:"nine thousand nine hundred twenty-three"
Input:1234
Output:"one thousand two hundred thirty-four"
This solution efficiently converts a number into words using a combination of recursive functions and predefined mappings. By breaking the number into manageable chunks, we can easily handle any number, regardless of its size.