HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Integer-to-string conversion using recursion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conversionrecursionusingstringinteger

Problem

Adapt the ideas of printd to write recursive version of itoa; that is, convert integer into a string by calling a recursive routine

Here is the implementation of printd:

void printd(int n) {
    if(n < 0)
        putchar('-');
    if(n / 10)
        printd(n / 10);
    putchar(n % 10 + '0')l
}


And here is my solution:

int itoa(int n, char s[]) {
    int i;

    if(n < 0) {
        n *= -1; 
    }

    i = 0;
    if(n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* next free slot in array */
}


As you can see, my version of itoa is a little bit different than the one presented in the book. It returns a variable i that represents the index of the next free slot in array, at every step it fills the next empty slot with the null character. At the deepest level of recursion, it returns 1.

Could you review my exercise?

Solution

There are two bugs in printd():

  • The last character is an l instead of a semicolon.



  • If n is negative, it prints a negative sign before each digit.



Your itoa() also has a bug in handling negative input. It always stringifies the absolute value of n.

Your strategy to use the return value to determine which array element to write to seems like a good idea. I think it would be more user friendly, though, to say that you are returning the strlen() of the output.

int itoa(int n, char s[]) {
    int i = 0;

    if (n < 0) {
        s[0] = '-';
        return 1 + itoa(-n, s + 1);
    }

    if (n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* strlen(s), i.e. the next free slot in array */
}

Code Snippets

int itoa(int n, char s[]) {
    int i = 0;

    if (n < 0) {
        s[0] = '-';
        return 1 + itoa(-n, s + 1);
    }

    if (n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* strlen(s), i.e. the next free slot in array */
}

Context

StackExchange Code Review Q#39825, answer score: 6

Revisions (0)

No revisions yet.