forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodingjourney_3.c
More file actions
39 lines (35 loc) · 718 Bytes
/
codingjourney_3.c
File metadata and controls
39 lines (35 loc) · 718 Bytes
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 <limits.h>
extern int error;
long str2long_codingjourney_3 (const char *text) {
long result = 0L;
int negative = (*text == '-');
int valid = 0;
int done = 0;
text += negative;
while (!done && !error) {
char c = *(text++);
if (c >= '0' && c <= '9') {
valid = 1;
long before = result;
result = result * 10;
if (result / 10L != before) {
error = 1;
break;
}
before = result;
result += (c - '0');
if (result < before) {
int min = result == LONG_MIN;
done = *text == '\0';
error = !(negative && min && done);
}
} else if (c == '\0') {
result *= negative ? -1L : 1L;
error = !valid;
done = 1;
} else {
error = 1;
}
}
return result;
}