题目:运用printd函数的设计思想编写一个递归版本的itoa函数。即通过递归调用把整数转换为字符串。
在这里,我先将itoa函数写了出来,然后再写了一下递归版本的,很显然,递归版本的代码量远远小于正常版本的。但是相应的也要付出一定的空间代价。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
char *Itoa_special(int number, char *pstr);
char *Itoa(int number);
int main()
{
char *pstr = NULL;
pstr = (char *)malloc(sizeof(char) * 1000);
printf("%s", Itoa_special(-123, pstr));
return 0;
}
char *Itoa_special(int number, char *pstr)
{
static int nIdx = 0;
if(number < 0)
{
pstr[nIdx++] = '-';
number = -number;
}
if(number / 10)
{
Itoa_special(number / 10, pstr);
}
pstr[nIdx++] = number % 10 + '0';
pstr[nIdx] = '\0'; //下一次调用后会覆盖掉当前的'\0',最后一次保留
return pstr;
}
char* Itoa(int number)
{
void Reverse(char *szBuf);
char *p = NULL;
int Idx = 0;
p = (char *)malloc(sizeof(char) * 100);
if(number < 0)
{
p[Idx++] = '-';
number = -number;
}
while(number != 0)
{
p[Idx++] = number % 10 + '0';
number /= 10;
}
p[Idx] = '\0';
Reverse(p);
return p;
}
void Reverse(char *szBuf)
{
void Swap(char *szBuf_1, char *szBuf_2);
int i = 0;
int j = 0;
while(szBuf[j++] != '\0');
j -= 2;
while(i < j)
{
Swap(&szBuf[i], &szBuf[j]);
i++;
j--;
}
}
void Swap(char *szBuf_1, char *szBuf_2)
{
int nTmp = *szBuf_1;
*szBuf_1 = *szBuf_2;
*szBuf_2 = nTmp;
}