forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphil.c
More file actions
44 lines (35 loc) · 799 Bytes
/
phil.c
File metadata and controls
44 lines (35 loc) · 799 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
#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_phil (const char *str)
{
long l = 0;
long sign = 1;
long digit;
if (*str == '-') {
sign = -1;
str++;
}
if (!(*str))
goto fail;
while (*str) {
if (*str < '0' || '9' < *str)
goto fail;
digit = sign * (*str - '0');
if (l > LONG_MAX / 10 || l < LONG_MIN / 10)
goto fail;
l *= 10;
if ((sign == 1 && digit > LONG_MAX - l) || (sign == -1 && digit < LONG_MIN - l))
goto fail;
l += digit;
str++;
}
return l;
fail:
error = 1;
return l;
}