I wrote code to convert a decimal number to a corresponding alphabetical representation.
Examples:
1: A
2: B
.
.
.
26: Z
27: AA
.
.
.
703: AAA
Here is my approach:
void print(int n)
{
if( n > 0 )
{
n--;
print( n / 26 );
printf( "%c", ( n % 26 ) + 'A' );
}
}
The above code is working correctly. Can I optimize it in terms of readability?
What is the best way to do it?
Now, I want to modify the above code to work like this:
0: A
1: B
.
.
.
25: Z
26: AA
.
.
.
702: AAA
The obvious approach is to add 1 to the input decimal number and pass it to the function in the original code. How can I modify the first program to work it for the second case without adding 1?
After some observations, i have tried the below code & its working for the Case: 2
.
void print(int n)
{
if(n < 26)
printf("%c", n + 'A');
else
{
print(n / 26 - 1);
print(n % 26);
}
}
See output here.