-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8_String-to-Integer-atoi.cpp
More file actions
104 lines (101 loc) · 2.95 KB
/
8_String-to-Integer-atoi.cpp
File metadata and controls
104 lines (101 loc) · 2.95 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <string>
#include <cctype>
#include <climits>
using namespace std;
class Solution
{
public:
int myAtoi(string s)
{
int l = s.size();
int ans = 0;
for (int i = 0; i < l; ++i)
{
if (s[i] == '-' || s[i] == '+')
{
if (s[i + 1] == ' ' || isalpha(s[i + 1]))
{
return 0;
}
for (int j = i + 1; j < l; ++j)
{
if (ans == 0 && s[j] == '0')
{
continue;
}
if (!isdigit(s[j]))
{
break;
}
if (1LL * ans * 10 > INT_MAX)
{
if (s[i] == '-')
{
return INT_MIN;
}
return INT_MAX;
}
ans *= 10;
if (1LL * ans + (s[j] - '0') > INT_MAX)
{
if (s[i] == '-')
{
return INT_MIN;
}
return INT_MAX;
}
ans += s[j] - '0';
}
if (s[i] == '-')
{
return -ans;
}
return ans;
}
if (s[i] == ' ')
{
continue;
}
if (isdigit(s[i]))
{
for (int j = i; j < l; ++j)
{
if (ans == 0 && s[j] == '0')
{
continue;
}
if (!isdigit(s[j]))
{
break;
}
if (1LL * ans * 10 > INT_MAX)
{
return INT_MAX;
}
ans *= 10;
if (1LL * ans + (s[j] - '0') > INT_MAX)
{
if (s[i] == '-')
{
return INT_MIN;
}
return INT_MAX;
}
ans += s[j] - '0';
}
return ans;
}
if (!isdigit(s[i]))
{
return 0;
}
}
return ans;
}
};
// 做一个属于自己的stoi
// 考虑第一个遇到的的字符为什么字符
// 若为alpha,则返回0
// 若为+/-, 则从第二位开始往后历遍,遇到数字开头的'0'跳过,直至遇到第一个非数字截至, 然后返回 +/- sum
// 若为' ', 跳过
// 若为数字,则从第二位开始往后历遍,遇到数字开头的'0'跳过,直至遇到第一个非数字截至, 然后返回sum