-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0008.cpp
45 lines (38 loc) · 917 Bytes
/
0008.cpp
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
class Solution {
public:
int myAtoi(string s) {
while (!s.empty() && s[0] == ' ')
s.erase(s.begin());
if (s.empty())
return 0;
bool isNeg = false;
if (s[0] == '+')
{
s.erase(s.begin());
}
else if (s[0] == '-')
{
isNeg = true;
s.erase(s.begin());
}
int64_t x = 0;
while (!s.empty() && s[0] >= '0' && s[0] <= '9')
{
auto digit = s[0] - '0';
s.erase(s.begin());
x = x*10 + digit;
if (x > std::numeric_limits<int>::max())
break;
}
if (isNeg)
{
x = -x;
x = max<int64_t>(std::numeric_limits<int>::min(), x);
}
else
{
x = min<int64_t>(std::numeric_limits<int>::max(), x);
}
return x;
}
};