forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenaud.c
More file actions
64 lines (59 loc) · 1.15 KB
/
renaud.c
File metadata and controls
64 lines (59 loc) · 1.15 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "str2long.h"
static int char2dig(char c)
{
if ((c >= '0') && (c <= '9'))
return (c - '0');
return -1;
}
#define NB_DIG (int)log10(LONG_MAX)
long str2long_renaud (const char *str)
{
error = 1;
long value = 1;
int digit;
int index = 0;
int lead_zero = 0;
if (str[0] == '-') {
value = -1;
str++;
}
//remove leading 0
while (str[0] == '0')
{
str++;
lead_zero = 1;
}
// special case for 0
if (str[0] == '\0')
{
// error: case "-\0"
if (lead_zero == 0)
return 0L;
error = 0;
return 0L;
}
if ((digit = char2dig(str[index++])) == -1)
return 0L;
value *= digit;
if (value > 0) {
while ((digit = char2dig(str[index])) != -1) {
/* check that value * 10 + cur_digit isn't too big */
if ((index >= NB_DIG) && (value > ((LONG_MAX - digit) / 10)))
return 0;
value = (value * 10) + digit;
index++;
}
} else {
while ((digit = char2dig(str[index])) != -1) {
/* check that value * 10 - cur_digit isn't too small */
if ((index >= NB_DIG) && (value < ((LONG_MIN + digit) / 10)))
return 0;
value = (value * 10) - digit;
index++;
}
}
if (str[index] != '\0')
return 0L;
error = 0;
return value;
}