Search code examples
crecursionitoa

itoa recursively


I have been trying to write a recursive version of function itoa, the code is shown below.

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

     if(n / 10 != 0)
         itoa(n/10, s);
     else if(n < 0)
         i = 1; /* s[0] is allready taken by - sign */
     else 
         i = 0; /* reset i to 0 */

     if(n < 0) {
          s[0] = '-';
     }

     s[i++] = abs(n % 10) + '0';
     s[i] = '\0';
}

But the code is not ideal. It uses a static variable and probably is not executing as fast as it should be. I am trying to achieve a O(n) algorithm. Could anyone show me a better way? I also think that static variable is not necesary, but I'm not pretty sure how to avoid it. Should I break the function into two inorder to avoid the static variable?


Solution

  • If you want to solve it recursively, an easier approach might be to return the last index:

    int itoa(int n, char s[])
    {
        int i =  0;         
    
        if(n / 10 != 0)
            i = itoa(n/10, s);
        else if(n < 0)
            s[i++] = '-';
    
        s[i++] = abs(n % 10) + '0';
        s[i] = '\0';
    
        return i;
    }
    

    You could also solve it using pointers:

    char * itoa(int n, char * s)
    {
        char * dest = s;
    
        if(n / 10 != 0)
            dest = itoa(n/10, dest);
        else if(n < 0)
            *dest++ = '-';
    
        *dest++ = abs(n % 10) + '0';
        *dest = '\0';
    
        return dest;
    }
    

    However on thing to note is that this implementation is prone to buffer overflows. You need to be certain that you have allocated a sufficiently large buffer to fit the entire ascii representation of the integer. A good idea would be to include some boundary checking.