From e8bd1d3cc26edd2bea198152f6fe167206201ec5 Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Sat, 4 Dec 2021 08:37:38 +0800 Subject: 3.4 --- 3/4.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/3/4.c b/3/4.c index 92d8283..1ba196c 100644 --- a/3/4.c +++ b/3/4.c @@ -4,13 +4,14 @@ #define MAXLEN 50 -// Explanation of the error: +// xplanation of the error: // In itoa, for largest negative number, n = -n overflows // resulting in n = INT_MIN (wraps around) causing a god awful mess. void itoa(int n, char s[]); void reverse(char s[]); +/* Fixes itoa function to handle the largest negative number */ int main(int argc, char *argv[]) { char s[MAXLEN]; @@ -22,18 +23,22 @@ int main(int argc, char *argv[]) { } void itoa(int n, char s[]) { - int i, sign; + int i; i = 0; - - if ((sign = n) < 0) - n = -n; - do { - s[i++] = n % 10 + '0'; - } while ((n /= 10) > 0); + if (n >= 0) { + do { + s[i++] = n % 10 + '0'; + } while ((n /= 10) > 0); + } + else { + do { + s[i++] = -(n % 10) + '0'; + } while ((n /= 10) <= -1); + } - if (sign < 0) + if (n < 0) s[i++] = '-'; s[i] = 0; -- cgit v1.2.3