-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path8.string-to-integer-atoi.cpp
68 lines (65 loc) · 1.51 KB
/
8.string-to-integer-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
63
64
65
66
67
68
/*
* @lc app=leetcode id=8 lang=cpp
*
* [8] String to Integer (atoi)
*/
// @lc code=start
#include <string>
#include <iostream>
using namespace std;
class Solution
{
public:
int myAtoi(string str)
{
if (str.length() == 0)
return 0;
int base = 0, i = 0, sign = 1;
while (i < str.length() && str.at(i) == ' ')
{
i++;
}
if (i < str.length() && (str.at(i) == '-' || str.at(i) == '+'))
{
if (str.at(i) == '-')
sign = -1;
else
sign = 1;
i++;
}
while (i < str.length() && str.at(i) >= '0' && str.at(i) <= '9')
{
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str.at(i) - '0' > 7))
{
if (sign == 1)
return INT_MAX;
else
return INT_MIN;
}
base = base * 10 + (str.at(i++) - '0');
}
return base * sign;
}
};
// @lc code=end
int main()
{
Solution s;
string a[] = {"",
// "-",
// "+",
// "+-",
// "-+",
// "+-1",
// "-+1",
// " -42",
// " 42",
// "words and 987",
// "-91283472332",
"2147483646"};
for (const auto &str : a)
{
int a = s.myAtoi(str);
cout << a << endl;
}
}