/
markus_2.c
45 lines (38 loc) · 1.06 KB
/
markus_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
44
45
#include "str2long.h"
long str2long_markus_2 (const char* str) {
unsigned int idx;
long out = 0;
if (str[0] == '-') {
for (idx=1; ((int)str[idx] >= (int)'0') && ((int)str[idx] <= (int)'9'); ++idx) {
long digit = (long)str[idx] - (long)'0';
out *= 10;
if ((LONG_MIN - out) > -digit) {
error = 1;
return 0;
}
out -= digit;
}
if (idx == 1)
{ /* Loop didn't loop -> No digit or empty string. */
error = 1;
return 0;
}
}
else {
for (idx=0; ((int)str[idx] >= (int)'0') && ((int)str[idx] <= (int)'9'); ++idx) {
long digit = (long)str[idx] - (long)'0';
out *= 10;
if ((LONG_MAX - out) < digit) {
error = 1;
return 0;
}
out += digit;
}
if (idx == 0)
{ /* Loop didn't loop -> No digit or empty string. */
error = 1;
return 0;
}
}
return out;
}