forked from regehr/str2long_contest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchucky_2.c
57 lines (48 loc) · 1.08 KB
/
chucky_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
46
47
48
49
50
51
52
53
54
55
56
57
#include "str2long.h"
static long MULT_MIN = LONG_MIN / 10;
long str2long_chucky_2 (const char * s) {
char c = *s++;
// string is empty
if (!c) {
error = 1;
return error = 1;
}
// if it actually is negative, remember that and get the next char
_Bool isNegative = 0;
if (c == '-') {
isNegative = 1;
c = *s++;
}
// now handle the numbers part
long number = 0; // we keep 'number' negative below
do {
// if non digit, error
if (!(c >= '0' && c <= '9')) {
error = 1;
return 1;
}
int digit = -(c - '0'); // negative since we're trying to stay negative
// since we have a new digit, need to shift number; make sure it's safe
if (number < MULT_MIN) {
error = 1;
return 1;
}
number *= 10;
// check if it's safe to add the new digit and do so
if (LONG_MIN - number > digit) {
error = 1;
return 1;
}
number += digit;
} while ((c = *s++));
// flip the signs back around if needed
if (!isNegative) {
// as long as it's safe...
if (LONG_MAX * -1 > number) {
error = 1;
return 1;
}
number *= -1;
}
return number; // success!
}