blob: c229dd78091f9c14409e31e16bbd4b7c0e62ab27 (
plain)
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
|
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
char * skip_space(char *s) {
while (isspace(*s)) s++;
return s;
}
int symbol(char **ps) {
char *s = *ps;
if (*s == '+') {
s++;
*ps = s;
return 1;
}
if (*s == '-') {
s++;
*ps = s;
return -1;
}
return 1;
}
int64_t read_num(char *s) {
int64_t r = 0;
int i = 0;
while (1) {
if (s[i] < '0' || s[i] > '9') {
return r;
}
r = r * 10 + s[i] - '0';
if (r > ((int64_t)1 << 32)) {
return r;
}
i++;
}
return r;
}
int myAtoi(char* s) {
s = skip_space(s);
int sym = symbol(&s);
int64_t r = read_num(s);
if (sym > 0) {
if (r > 2147483647) r = 2147483647;
} else {
if (r > 2147483648) r = 2147483648;
}
return sym > 0 ? r : -r;
}
int main() {
printf("%d\n", myAtoi("123"));
printf("%d\n", myAtoi(" +123"));
printf("%d\n", myAtoi("0000000000012345678"));
printf("%d\n", myAtoi("-123111111111111111"));
}
|