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?