2 5dc21454 2023-07-14 jrmu * Exercise 3-4. In a two's complement number representation, our version of
3 5dc21454 2023-07-14 jrmu * itoa does not handle the largest negative number, that is, the value of n
4 5dc21454 2023-07-14 jrmu * equal to -(2^(wordsize-1)). Explain why not. Modify it to print that value
5 5dc21454 2023-07-14 jrmu * correctly, regardless of the machine on which it runs.
8 5dc21454 2023-07-14 jrmu /* In the step n = -n, it is not possible to negate the largest negative
9 5dc21454 2023-07-14 jrmu * number without integer overflow.
12 5dc21454 2023-07-14 jrmu #include <string.h>
13 5dc21454 2023-07-14 jrmu #include <stdio.h>
14 5dc21454 2023-07-14 jrmu #include <limits.h>
16 5dc21454 2023-07-14 jrmu void reverse(char s[]) {
17 5dc21454 2023-07-14 jrmu int c, i, j;
18 5dc21454 2023-07-14 jrmu for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
20 5dc21454 2023-07-14 jrmu s[i] = s[j];
25 5dc21454 2023-07-14 jrmu void itoa(int n, char s[]) {
26 5dc21454 2023-07-14 jrmu int i, sign;
28 5dc21454 2023-07-14 jrmu if ((sign = n) < 0)
32 5dc21454 2023-07-14 jrmu s[i++] = u % 10 + '0';
33 5dc21454 2023-07-14 jrmu } while ((u /= 10) > 0);
34 5dc21454 2023-07-14 jrmu if (sign < 0)
35 5dc21454 2023-07-14 jrmu s[i++] = '-';
36 5dc21454 2023-07-14 jrmu s[i] = '\0';
40 5dc21454 2023-07-14 jrmu int main() {
41 5dc21454 2023-07-14 jrmu /* word size is 32 bits */
42 5dc21454 2023-07-14 jrmu char s[100];
43 5dc21454 2023-07-14 jrmu int i = -147483648;
45 5dc21454 2023-07-14 jrmu printf("Actual: %s\n", s);
46 5dc21454 2023-07-14 jrmu printf("Expect: %s\n", "-147483648");
47 5dc21454 2023-07-14 jrmu i = INT_MIN+1;
49 5dc21454 2023-07-14 jrmu printf("Actual: %s\n", s);
50 5dc21454 2023-07-14 jrmu printf("Expect: %d\n", INT_MIN+1);
51 5dc21454 2023-07-14 jrmu i = INT_MIN;
53 5dc21454 2023-07-14 jrmu printf("Actual: %s\n", s);
54 5dc21454 2023-07-14 jrmu printf("Expect: %d\n", INT_MIN);