Given a number, print words for individual digits. It is not allowed to use if or switch.
Input: n = 123 Output: One Two Three Input: n = 350 Output: Three Five Zero
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use an array of strings to store digit to word mappings. Below are steps.
Let input number be n.
- Create an array of strings to store digit to word mapping.
- Create another array digits to store individual digits of n.
- Traverse digits of n and store them in digits. Note that standard way of traversal by repeated storing n%10 and doing n = n/10, traverses digits in reverse order.
- Traverse the digits array from end to beginning and print words using the mapping created in step 1.
Below is the implementation of above idea.
Three Five Zero
Thanks to Utkarsh Trivedi for suggesting above solution.
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.
- Program to print the given digit in words
- C++ program to print unique words in a file
- Find and print duplicate words in std::vector<string> using STL functions
- Print numbers with digits 0 and 1 only such that their sum is N
- Print all numbers less than N with at-most 2 unique digits
- C Program to Print all digits of a given number
- Print last k digits of a^b (a raised to power b)
- Print first k digits of 1/n where n is a positive integer
- Print all n-digit numbers whose sum of digits equals to given sum
- Print a number containing K digits with digital root D
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1
- Print all numbers in given range having digits in strictly increasing order
- Print a number strictly less than a given number such that all its digits are distinct.
- Switch Statement in C/C++
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
- Nested switch statement in C++
- Using range in switch case in C/C++
- Nested switch case
- Numbers with sum of digits equal to the sum of digits of its all prime factor