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.
- 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 first k digits of 1/n where n is a positive integer
- Print all numbers less than N with at-most 2 unique digits
- Print last k digits of a^b (a raised to power b)
- 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 a number strictly less than a given number such that all its digits are distinct.
- Switch Statement in C/C++
- Using range in switch case in C/C++
- Nested switch statement in C++
- Nested switch case
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number