forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathethan.c
More file actions
45 lines (37 loc) · 684 Bytes
/
ethan.c
File metadata and controls
45 lines (37 loc) · 684 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
39
40
41
42
43
44
45
#include "str2long.h"
long str2long_ethan(const char *str) {
long m = 1;
error = 1;
// Validate the string and find its end.
if (*str == '-') {
str++;
m = -1;
}
const char *p = str;
if (*p == '\0')
return 0;
while (*p != '\0') {
if (!isdigit(*p))
return 0;
p++;
}
// Compute the value.
long l = 0;
for ( ; ; ) {
p--;
long d = *p-'0';
if ((m < -1 && LONG_MIN/m < d) || (m > 0 && LONG_MAX/m < d))
return 0;
d *= m;
if ((d < 0 && LONG_MIN-d > l) || (d > 0 && LONG_MAX-d < l))
return 0;
l += d;
if (p == str)
break;
if ((m < 0 && LONG_MIN/10 > m) || (m > 0 && LONG_MAX/10 < m))
return 0;
m *= 10;
}
error = 0;
return l;
}