-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathatoi.c
67 lines (57 loc) · 1.17 KB
/
atoi.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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
static int myAtoi(char* str)
{
char *s;
long n = 0;
int sign = 0;
while (*str == ' ' || *str == '\t') {
str++;
}
if (*str == '-') {
if (isdigit(*++str)) {
sign = 1;
} else {
return 0;
}
}
if (*str == '+') {
if (isdigit(*++str)) {
sign = 0;
} else {
return 0;
}
}
for (s = str; *s != '\0'; s++) {
if (isdigit(*s)) {
int d = *s - '0';
if (sign) {
if (-n < (INT_MIN + d) / 10) {
n = INT_MIN;
break;
}
} else {
if (n > (INT_MAX - d) / 10) {
n = INT_MAX;
break;
}
}
n = n * 10 + d;
} else {
break;
}
}
return sign ? -n : n;
}
int main(int argc, char **argv)
{
if (argc != 2) {
printf("Usage: ./atoi 123\n");
exit(-1);
}
int n = myAtoi(argv[1]);
printf("n = %d %x\n", n, n);
return 0;
}