forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyang.c
More file actions
54 lines (44 loc) · 866 Bytes
/
yang.c
File metadata and controls
54 lines (44 loc) · 866 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
46
47
48
49
50
51
52
53
#include "str2long.h"
long str2long_yang (const char *s)
{
unsigned long v = 0;
unsigned num_of_elem = 0;
unsigned char neg = 0;
unsigned char c;
assert(s && "NULL string!");
error = 0;
if (*s == '-') {
neg = 1;
s++;
}
if (*s == '\0')
goto err;
/* skip the leading 0s, thus accept strings like
0000000000000000000000000000000123 */
while (*s == '0')
s++;
while ((c = *s++) != '\0') {
if ((c < '0') || (c > '9'))
goto err;
num_of_elem++;
if (num_of_elem > 19)
goto err;
c -= '0';
v = v * 10 + c;
}
if (neg) {
if (v > (-(unsigned long)(LONG_MIN)))
goto err;
else if (v == (unsigned long)(LONG_MIN))
return v;
return -((long)v);
}
else {
if (v > (unsigned long)(LONG_MAX))
goto err;
return (long)v;
}
err:
error = 1;
return -1;
}