-
Notifications
You must be signed in to change notification settings - Fork 1
/
6.c
90 lines (71 loc) · 2.01 KB
/
6.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
#include <stdio.h>
#include <string.h>
#include <limits.h>
#define LIM 99999
/**
* Q: In a two’s complement number representation, our version of itoa does not
* handle the largest negative number, that is, the value of n equal to
* -(2^(wordsize-1)). Explain why not.
*
* A: The largest negative number doesn't fit into an int when its signal is
* changed, i.e., it is greater than INT_MAX.
*/
/* reverse: reverse string s in place */
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/**
* Converts integer x to a string. The converted number must be padded with blanks
* on the left if necessary to make it wide enough.
*
* @param int x The integer to be converted
* @param char[] s The resultant string
* @param int w The minimum field width
*
* @return void
*/
void itoa(int x, char s[], int w)
{
int i = 0, j = 0;
/**
* We cast input int to a long to handle the case of INT_MIN.
* Remember that int interval is [-2147483648, 2147483647].
*/
long n = x;
if (n < 0) /* record sign */
n = -n; /* make n positive */
/* generate digits in reverse order */
do {
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (x < 0)
s[i++] = '-';
/* Adding padding characters to match width field */
for (j = (i+1); j <= w; j++) {
s[i++] = ' ';
}
s[i] = '\0';
reverse(s);
}
main()
{
char result[LIM];
itoa(958585, result, 10);
printf("itoa(958585) => '%s'\n", result);
itoa(10, result, 10);
printf("itoa(10) => '%s'\n", result);
itoa(958000, result, 10);
printf("itoa(958000) => '%s'\n", result);
itoa(-914124, result, 10);
printf("itoa(-914124) => '%s'\n", result);
itoa(INT_MIN+1, result, 10);
printf("itoa(INT_MIN+1) => '%s'\n", result);
itoa(INT_MIN, result, 10);
printf("itoa(INT_MIN) => '%s'\n", result);
}