![]() |
VOOZH | about |
Given a number N, the task is to convert every digit of the number into words.
Examples:
Input: N = 1234
Output: One Two Three Four
Explanation:
Every digit of the given number has been converted into its corresponding word.Input: N = 567
Output: Five Six Seven
Approach: The idea is to traverse through every digit of the number and use switch-case. Since there are only ten possible values for digits, ten cases can be defined inside a switch block. For each digit, its corresponding case block will be executed and that digit will get printed in words.
Below is the implementation of the above approach:
One Two Three
Time Complexity: O(L), Here L is the length of the string
Auxiliary Space: O(1), As constant extra space is used.
Recursive Approach
The idea is to recursively call the function till the number becomes zero by dividing it by 10 and storing the remainder in a variable. Then we print the digit from the string array as the digit will store the index of the number to be printed from the array.
we print the number after the recursive call to maintain the order of digits in the input number, if we print before the recursive function call the digit name will be printed in reversed order. Since we are dividing n by 10 in each recursive call the recurrence relation will be T(n) = T(n/10) + 1
Below is the implementation of the above approach:
one two three
Time Complexity: O(log10 n)
Auxiliary Space: O(log10 n) for recursive call stack
Approach 3 : By using Python Dictionary.
Algorithm -
One Two Three
Time Complexity: O(n), where n is the length of string
Auxiliary Space: O(1)
Related Article: Print individual digits as words without using if or switch