forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
andrewh_3.c
55 lines (50 loc) · 1.19 KB
/
andrewh_3.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
#include "str2long.h"
long str2long_andrewh_3(const char *s) {
char c = *s++;
unsigned long safe;
long sign;
unsigned long lim;
if (c == '-') {
c = *s++;
safe = (LONG_MAX - (9 - 1)) / 10;
lim = ((unsigned long)LONG_MAX) + 1;
sign = -1;
} else {
safe = (LONG_MAX - 9) / 10 ;
lim = LONG_MAX;
sign = 0;
}
if (!isdigit(c)) {
error = 1;
return 0;
}
unsigned long curr = 0;
// don't check overflow until it's a concern
while (isdigit(c) && curr <= safe) {
curr = 10 * curr + (c - '0');
c = *s++;
}
if (c != '\0') {
if (!isdigit(c)) {
error = 1;
return 0;
}
int digit = c - '0';
if ((lim - digit) / 10 < curr) {
error = 1;
return 0;
}
curr = 10 * curr + digit;
}
if (*s != '\0') {
error = 1;
return 0;
}
// curr is correct and in range for its sign. Now we just want to
// negate it (if we need to.) Rely on "usual implementation defined
// behavior" and 2s-complement, i.e. either long -> unsigned long or
// unsigned long -> long just keeps the same bits.
// (This can incur unsigned overflow but that's defined to be OK.)
long ret = ((curr ^ sign) - sign);
return ret;
}