forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.c
55 lines (46 loc) · 1.08 KB
/
8.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
#include <stdio.h>
#include <stdint.h>
int myAtoi(char *str) {
int64_t ret = 0;
int sign = 1;
char *p = str;
/* ignore white spaces */
while (*p == ' ') p++;
if (*p == '-') {
sign = -1;
p++;
}
else if (*p == '+') {
sign = 1;
p++;
}
while (*p >= '0' && *p <= '9') {
ret = ret * 10 + (*p - '0');
if (ret - 1 > INT32_MAX) ret = (int64_t)INT32_MAX + 1;
//printf("%ld\n", ret);
p++;
}
if (sign == -1) ret = -ret;
if (ret > INT32_MAX) ret = INT32_MAX;
if (ret < INT32_MIN) ret = INT32_MIN;
return (int)ret;
}
int main() {
char *s[12];
s[0] = " 123 ";
s[1] = "123.4";
s[2] = "-1234";
s[3] = "2147483646";
s[4] = "2147483647";
s[5] = "2147483648";
s[6] = "-2147483647";
s[7] = "-2147483648";
s[8] = "-2147483649";
s[9] = "-1";
s[10] = "+-2";
s[11] = "9223372036854775809";
int i;
for (i = 0; i < 12; i++)
printf("%d\n", myAtoi(s[i]));
return 0;
}