diff options
| author | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 08:37:38 +0800 |
|---|---|---|
| committer | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 08:37:38 +0800 |
| commit | e8bd1d3cc26edd2bea198152f6fe167206201ec5 (patch) | |
| tree | 495ef4cd3086ab596a51afc7984686a77a31c832 /3 | |
| parent | 273eacec3c2b291c991fad15e95d6f09bbb0978d (diff) | |
| download | k&r-exercises-e8bd1d3cc26edd2bea198152f6fe167206201ec5.tar.gz | |
3.4
Diffstat (limited to '3')
| -rw-r--r-- | 3/4.c | 23 |
1 files changed, 14 insertions, 9 deletions
@@ -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; |
