Skip to content

Commit 0f3101b

Browse files
committed
revise answer
1 parent 10e47b6 commit 0f3101b

File tree

1 file changed

+17
-47
lines changed

1 file changed

+17
-47
lines changed

chapter04/4-13.c

Lines changed: 17 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,43 @@
11
/*
22
* Exercise 4-13. Write a recursive version of the function reverse(s), which
33
* reverses the string s in place.
4+
*
45
* By Faisal Saadatmand
56
*/
67

78
#include <stdio.h>
89
#include <string.h>
9-
#include <limits.h>
10+
11+
#define MAXLEN 1000
1012

1113
/* functions */
1214
void reverse(char []);
13-
void itoa(int, char []);
1415

1516
/* reverse function: reverse string s in place, recursive version */
1617
void reverse(char s[])
1718
{
18-
int c, j;
19-
static int i;
20-
21-
j = (strlen(s) - 1) - i;
22-
if (j >= 0) {
23-
c = s[i];
24-
s[i++] = s[j];
25-
s[j] = c;
19+
int c;
20+
static unsigned long i = 0, j = 0;
21+
22+
if (j < strlen(s) - 1) {
23+
++j;
2624
reverse(s);
2725
}
28-
}
29-
30-
/* itoa: convert n to characters in s */
31-
void itoa(int n, char s[])
32-
{
33-
int i, sign, lastDigit;
34-
35-
lastDigit = 0;
36-
if (n == INT_MIN) { /* add check for size */
37-
lastDigit = (n % 10 * -1) + '0'; /* extract save the last digit */
38-
n -= 1; /* reduce n to fit INT_MAX */
26+
if (i < j) {
27+
c = s[i];
28+
s[i++] = s[j];
29+
s[j--] = c;
3930
}
40-
41-
if ((sign = n) < 0) /* record sign */
42-
n = -n;
43-
44-
i = 0;
45-
do { /* generate digits in reverse order */
46-
s[i++] = n % 10 + '0'; /* get next digit */
47-
} while ((n /= 10) > 0);
48-
49-
if (sign < 0)
50-
s[i++] = '-';
51-
52-
if (lastDigit > 0) /* put back saved last digit */
53-
s[0] = lastDigit;
54-
55-
s[i] = '\0';
56-
57-
reverse(s);
5831
}
5932

6033
int main(void)
6134
{
62-
int intValue;
63-
char stringNumber[64];
64-
65-
printf("Enter integer to convert to a string: ");
66-
scanf("%i", &intValue);
67-
68-
itoa(intValue, stringNumber);
35+
char str[MAXLEN];
6936

70-
printf("%s\n", stringNumber);
37+
printf("Enter a string to reverse:\n");
38+
scanf("%s", str);
39+
reverse(str);
40+
printf("%s\n", str);
7141

7242
return 0;
7343
}

0 commit comments

Comments
 (0)