-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1008. 字符串转整数 (atoi).cpp
62 lines (62 loc) · 1.11 KB
/
1008. 字符串转整数 (atoi).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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
public:
int myAtoi(string str) {
int i = 0;
if (str.size() == 0)
{
return 0;
}
while (str[i] == ' '&&i<str.size())
{
i++;
}
if (i == str.size() || isalpha(str[i]))
{
return 0;
}
string temp = "";
temp += str[i];
i++;
while (str[i] != ' '&&!isalpha(str[i]) && i<str.size() && str[i] != '+'&& str[i] != '-')
{
temp += str[i];
i++;
}
map<char, int> count;
for (int j = 0; j < temp.size(); j++)
{
count[temp[j]] += 1;
}
if (count['+'] == temp.size() || count['-'] == temp.size() || count['+'] + count['-']>1)
{
return 0;
}
if (temp[0] == '+')
{
string t = "";
for (int i = 1; i < temp.size(); i++)
{
t += temp[i];
}
temp = t;
}
if (temp.size()>10 && temp[0] != '-')
{
return 2147483647;
}
if (temp.size() == 10 && temp[0] != '-' && temp >= "2147483647")
{
return 2147483647;
}
if (temp.size()>11 && temp[0] == '-')
{
return -2147483648;
}
if (temp.size() == 11 && temp[0] == '-' && temp > "-2147483648")
{
return -2147483648;
}
long long int result = stoll(temp);
return (int)result;
}
};