forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matthewf.c
38 lines (34 loc) · 926 Bytes
/
matthewf.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
#include "str2long.h"
long str2long_matthewf(const char *s) {
long val = 0;
int negative = 0;
if (*s == '-') {
negative = 1;
++s;
}
for (;*s != '\0'; ++s) {
if (*s < '0' || *s > '9') {
/* Non-numeric character; bail out. */
error = 1;
return -1;
} else {
long d = *s - '0'; /* digit value */
if (negative) {
if ((LONG_MIN + d) / 10 > val) {
/* We're about to underflow. */
error = 1;
return -1;
}
val = val * 10 - d;
} else {
if ((LONG_MAX - d) / 10 < val) {
/* We're about to overflow. */
error = 1;
return -1;
}
val = val * 10 + d;
}
}
}
return val;
}