forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjeffrey.c
More file actions
68 lines (61 loc) · 1.55 KB
/
jeffrey.c
File metadata and controls
68 lines (61 loc) · 1.55 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
65
66
67
68
#include "str2long.h"
#if 0
long str2long_jeffrey(const char *str) {
bool negative = false;
if (str[0] == '-') {
negative = true;
++str;
}
if (*str == '\0')
return error = 1;
unsigned long accum = 0;
char c;
while (c = *str++) {
if (c < '0' || c > '9')
return error = 1;
unsigned long prev_accum = accum;
accum = accum * 10 + (c - '0');
if (accum < prev_accum) // Overflow.
return error = 1;
}
long result;
if (negative) {
result = -accum; // Implementation-defined, likely 2's complement.
if (result > 0) // Overflow.
return error = 1;
} else {
result = accum; // Implementation-defined, likely 2's complement.
if (result < 0) // Overflow.
return error = 1;
}
return result;
}
#else
//This one generates worse code, but is slightly shorter and doesn't
//depend on the unsigned->signed conversion:
#include <limits.h>
long str2long_jeffrey(const char *str) {
bool positive = true;
if (str[0] == '-') {
positive = false;
++str;
}
if (*str == '\0')
return error = 1;
long accum = 0;
char c;
while (c = *str++) {
if (c < '0' || c > '9')
return error = 1;
if ((LONG_MIN + (c - '0')) / 10 > accum)
return error = 1;
accum = accum * 10 - (c - '0');
}
if (positive) {
if (accum < -LONG_MAX)
return error = 1;
return -accum;
}
return accum;
}
#endif