Cプログラミング言語(第2版)4-12
printd関数の設計思想を用いて再帰バージョンのitoa関数を記述し,すなわち再帰呼び出しによって整数を文字列に変換する
下は私が自分で書いたので、笑ってください.
#include <stdlib.h>
#include <stdio.h>
/* : itoa, itoa int value , , value unsigned , utoa*/
char *utoa(unsigned value, char *digits, int base)
{
char *s, *p;
s = "0123456789abcdef"; /* don't care if s is in
* read-only memory
*/
if (base == 0)
base = 10;
if (digits == NULL || base < 2 || base > 36)
return NULL;
if (value < (unsigned) base) {
digits[0] = s[value];
digits[1] = '\0';
} else {
for (p = utoa(value / ((unsigned)base), digits, base);
*p;
p++);
utoa( value % ((unsigned)base), p, base);
}
return digits;
}
char *itoa(int value, char *digits, int base)
{
char *d;
unsigned u; /* assume unsigned is big enough to hold all the
* unsigned values -x could possibly be -- don't
* know how well this assumption holds on the
* DeathStation 9000, so beware of nasal demons
*/
d = digits;
if (base == 0)
base = 10;
if (digits == NULL || base < 2 || base > 36)
return NULL;
if (value < 0) {
*d++ = '-';
u = -value;
} else
u = value;
utoa(u, d, base);
return digits;
}
int main(){
int num = 12;
char* digits;
digits = new char[10];
digits = itoa(num,digits,16);
printf("%s
",digits);
return 0;
}
下は私が自分で書いたので、笑ってください.
#include<stdio.h>
void itoa(int n){
if(n<0)
{
putchar('-');
n=-n;
}
if(n/10)
itoa(n/10);
putchar(n%10+'0');
}
int main(){
int n=12345;
itoa(n);
printf("
");
return 0;
}