Since this is a homework problem, I just give you some pseudo-code on how to solve this. You will still have to implement it yourself.
Let us assume you get a number as input existing out of n digits: a1a2a3 ... an
Since the alphabet contains 26 letters, we want to split this number into groups of 1 or 2 digits and if we have a group of two digits, you have to check if the number is smaller than 27. The quickest way to do this is to make use of a recursive function. It is not the cleanest, but the quickest. Let us assume the recursive function is called decode
.
It is very easy to understand why a recursive function is needed. If we want to decode the number 25114. There are two paths we need to take, groups of 1 and groups of 2:
- group of 1: translate the last digit 4 into "D", and decode the remaining number 2511
- group of 2: check if the last two digits are smaller than 27, translate the last two digits 14 into N and decode the remaining number 251
In pseudo-code this looks like this:
# function decode
# input: the number n to decode
# a postfix string p representing the decoded part
function decode(n, p) {
# end condition: If the number is ZERO, I have decoded the full number
# only print and return
if (n == 0) { print p; return }
# group of 1: use integer division to extract the
# last digit as n%10 and
# remainder to decode is n/10
decode(n/10, concat(translate(n%10),p) )
# group of 2: use integer division to extract the
# last two digits as n%100 and
# remainder to decode is n/100
# This does not need to run if n < 10 or if n%100 > 26
if (n > 9 && n%100 <= 26) { decode(n/100, concat(translate(n%100),p) ) }
}
- The function
concat
concatenates two strings: concat("AA","BB")
returns "AABB"
- The function
translate(n)
converts a number n
into its corresponding alphabetic character. This can be written as sprintf("%c",64+n)
As is mentioned in the comments, this is not a very efficient method. This is because we do the same work over and over. If the input reads 25114, we will do the following steps in order:
step 1: translate(4), decode _2511_
step 1.1: translate(1), decode _251_
step 1.1.1: ...
step 1.2: translate(11), decode _25_
step 1.2.1: ...
step 2: translate(14), decode _251_
as you see, we have to decode 251 twice (in step 1.1 and step 2). This is very inefficient as we do everything more than ones.
To improve this, you can keep track of what you have done so far in a lookup table