forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobert.c
More file actions
45 lines (39 loc) · 1.44 KB
/
robert.c
File metadata and controls
45 lines (39 loc) · 1.44 KB
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
#include "str2long.h"
long str2long_robert(const char *str)
{
long result = 0;
int i;
/*error = 0;*/
if (str[0] == '-') {
for (i=1; str[i]; i++) {
int c = str[i];
if (c < '0' || '9' < c) {
error = 1;
return 0;
} else if (result < LONG_MIN/10) {
error = 1;
return 0;
} else if (result * 10 < (LONG_MIN + (c-'0'))) {
error = 1;
return 0;
} else
result = result * 10 - (c - '0');
}
} else {
for (i=0; str[i]; i++) {
int c = str[i];
if (c < '0' || '9' < c) {
error = 1;
return 0;
} else if (result > LONG_MAX/10) {
error = 1;
return 0;
} else if (result * 10 > (LONG_MAX - (c-'0'))) {
error = 1;
return 0;
} else
result = result * 10 + (c - '0');
}
}
return result;
}