forked from wuqingze/cprogramminglanguage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9.itoa-recursive.c
96 lines (76 loc) · 1.17 KB
/
9.itoa-recursive.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <limits.h>
void itoa(int n, char s[]);
void _itoa(int n);
void test01();
int main()
{
test01();
return 0;
}
void test00(){
char s[1024];
int n = INT_MAX;
itoa(n, s);
printf("s: %s, n: %d\n", s, n);
n = -2147483647;
itoa(n, s);
printf("s: %s, n: %d\n", s, n);
n = -INT_MAX;
itoa(n, s);
printf("s: %s, n: %d\n", s, n);
n = -0;
itoa(n, s);
printf("s: %s, n: %d\n", s, n);
n = 0;
itoa(n, s);
printf("s: %s, n: %d\n", s, n);
}
void test01(){
int n = INT_MAX;
_itoa(n);
printf("\n");
n = -2147483647;
_itoa(n);
printf("\n");
n = -INT_MAX;
_itoa(n);
printf("\n");
n = -0;
_itoa(n);
printf("\n");
n = 0;
_itoa(n);
printf("\n");
}
void _itoa(int n){
int isMin = 0;
if(n<0){
printf("-");
if(n == -n){
n += 1;
isMin = 1;
}
n = -n;
}
if(n/10)
_itoa(n /10);
printf("%d", isMin?(n%10+1):(n%10));
}
void itoa(int n, char s[])
{
if (n < 0) {
s[0] = '-';
n = -n;
}
if (n / 10)
itoa(n / 10, s);
int digits = 0;
int t = n;
while (t = t / 10)
digits++;
if (s[0] == '-')
digits++;
s[digits++] = n % 10 + '0';
s[digits] = '\0';
}