8. 字符串转换整数 (atoi)
为保证权益,题目请参考 8. 字符串转换整数 (atoi)(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <limits.h>
#include <string>
#include <ctype.h>
using namespace std;
class Solution
{
public:
int myAtoi(string str)
{
int res = 0;
int state = 1;
bool fu = false;
for (int i = 0; i < str.length(); ++i)
{
if (state == 1)
{
if (str[i] == ' ')
{
continue;
}
else if (str[i] == '+')
{
state = 2;
}
else if (str[i] <= '9' && str[i] >= '0')
{
res = res * 10 + int(str[i] - '0');
state = 2;
}
else if (str[i] == '-' && i + 1 < str.length() && str[i + 1] <= '9' && str[i + 1] >= '0')
{
res = 0 - int(str[i + 1] - '0');
i++;
state = 2;
fu = true;
}
else
{
break;
}
}
else if (state == 2)
{
if (str[i] <= '9' && str[i] >= '0')
{
int num = int(str[i] - '0');
if (fu)
{
num = -num;
}
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && num > INT_MAX % 10))
{
res = INT_MAX;
break;
}
if (res < INT_MIN / 10 || (res == INT_MIN / 10 && num < INT_MIN % 10))
{
res = INT_MIN;
break;
}
res = res * 10 + num;
}
else
{
break;
}
}
}
return res;
}
};
int main()
{
Solution so;
cout << so.myAtoi("2147483648") << endl;
return 0;
}
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
69
70
71
72
73
74
75
76
77
78
79
80
81
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
69
70
71
72
73
74
75
76
77
78
79
80
81