Print spelling for a given number

Posted by N.K. Chauhan on Mar 31, 2024

A number "n" is given, the task is to print spelling for n using recursion.

Example 1: Print spelling for 1000

Input: 1000
Output: One Zero Zero Zero

Example 2: Print spelling for 1

Input: 1
Output: One

Example 3: Print spelling for 895

Input: 895
Output: Eight Nine Five


Solutions

Method 1: Recursion

If we take modulo(%) of a number by 10 we get the last digit of that number i.e. 123 % 10 = 3; similarly if we divide a number by 10 and store the value in int we get the number except last digit i.e. int r = 123 / 10 = 12.

We can solve this problem easily using recursion, first we need to maintain an array to get spelling corresponding to a particular number. Now for every n we will take the last digit and get the corresponding spelling from the array and concat this at the end of f(n-1) recursive call result.

If n==0, that means the number is completely processed; return blank string ("") - base condition.

package com.cb.recursion;

/**
 * Recursion
 */
public class R6_PrintNumberSpelling {

     static String[] mappingArray = {"Zero", "One", "Two", "Three", "Four", 
            "Five", "Six", "Seven", "Eight", "Nine"};

    public static String printSpelling(int n) {
        if (n < 1)
            return "";

        int current = n % 10;
        int remaining = n / 10;

        return printSpelling(remaining) + " " + mappingArray[current];
    }

    public static void main(String[] args) {
        System.out.println(printSpelling(1000));
        System.out.println(printSpelling(1));
        System.out.println(printSpelling(126));
        System.out.println(printSpelling(895));
    }
}
One Zero Zero Zero
One
One Two Six
Eight Nine Five

Complexity
The time complexity of this solution is O(n) and space complexity is O(1).

Related


Sum of the digits of a given number

Calculate factorial of a given number

Print numbers from a given number to 0

Program for printing nth Fibonacci Number

Check if an integer array is sorted or not

Count ways to reach the nth stair

Print numbers from 0 to a given number

Program to solve "Tower of Hanoi" problem

Calculate the Power of a Number (n^p)

Write a program to reverse a string