Write code to convert a given number into words.
Input: 438237764 Output: forty three crore eighty two lakh thirty seven thousand seven hundred and sixty four Input: 999999 Output: nine lakh ninety nine thousand nine hundred and ninety nine Input: 1000 Output: one thousand Explanation:1000 in words is "one thousand"
We have already discussed an approach that handles numbers from 0 to 9999 in the previous post.
Solution: This approach can handle number till 20-digits long which are less than ULLONG_MAX (Maximum value for an object of type unsigned long long int). ULLONG_MAX is equal to 18446744073709551615 in decimal assuming compiler takes 8 bytes for storage of unsigned long long int.
Below representation shows place value chart for any 9 digits positive integer:
4 3 8 2 3 7 7 6 4 | | | | | | | | |__ ones' place | | | | | | | |__ __ tens' place | | | | | | |__ __ __ hundreds' place | | | | | |__ __ __ __ thousands' place | | | | |__ __ __ __ __ tens thousands' place | | | |__ __ __ __ __ __ hundred thousands' place | | |__ __ __ __ __ __ __ one millions' place | |__ __ __ __ __ __ __ __ ten millions' place |__ __ __ __ __ __ __ __ __ hundred millions' place
The idea is to divide the number into individual digits based on the above place value chart and handle them starting from the Most Significant Digit. Here’s a simple implementation that supports numbers having a maximum of 9 digits. The program can be easily extended to support any 20-digit number.
forty three crore eighty two lakh thirty seven thousand seven hundred and sixty four
- Time complexity: O(1).
The loop runs for a constant amount of time.
- Auxiliary space: O(1).
As no extra space is required.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.