forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrancois_2.c
44 lines (35 loc) · 816 Bytes
/
francois_2.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
#include "str2long.h"
/*
* if input matches ^-?[0-9]+\0$ and the resulting integer is
* representable as a long, return the integer; otherwise if
* the input is a null-terminated string, set error to 1 and
* return any value; otherwise behavior is undefined
*/
long str2long_francois_2(const char* s)
{
long sign = 1, result = 0;
if (*s == '-')
{
sign = -sign;
++s;
}
do
{
long digit;
if (*s < '0' || *s > '9')
{
error = 1;
break;
}
digit = *s - '0';
if (result < (LONG_MIN + digit) / 10 ||
result > (LONG_MAX - digit) / 10)
{
error = 1;
break;
}
result = result * 10 + digit * sign;
}
while (*++s);
return result;
}