-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.cpp
More file actions
106 lines (96 loc) · 1.93 KB
/
atoi.cpp
File metadata and controls
106 lines (96 loc) · 1.93 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
105
106
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
class Solution
{
public:
int myAtoi(string s)
{
string newS;
bool isNegative = false;
int len = s.length();
if (len == 0)
return 0;
for (int i = 0; i < len; i++)
{
char ch = s[i];
if (ch == ' ' && newS.empty())
{
continue;
}
if (ch != '-' && ch != '+' && !isdigit(ch) && newS.empty())
return 0;
if ((ch == '-' || ch == '+') && newS.empty())
{
isNegative = ch == '-';
newS.push_back(ch);
continue;
}
if (isdigit(ch))
{
newS.push_back(ch);
continue;
}
if (!isdigit(ch) && !newS.empty())
{
int convertToInt;
try
{
convertToInt = stoi(newS);
}
catch (const out_of_range &e)
{
string err = e.what();
cout << "Error outer catch: " << err << endl;
if (isNegative)
return INT32_MIN;
else
return INT32_MAX;
}
catch (...)
{
// cout << "Error catch all: " <<
return 0;
}
return convertToInt;
}
}
int convertToInt;
try
{
convertToInt = stoi(newS);
}
catch (const out_of_range &e)
{
string err = e.what();
cout << "Error outer catch: " << err << endl;
if (isNegative)
return INT32_MIN;
else
return INT32_MAX;
}
catch (...)
{
// cout << "Error catch all: " <<
return 0;
}
return convertToInt;
}
};
int main()
{
Solution sol;
// string s = " 4194 with words";
// string s = "42";
// string s = " -42";
// string s = "-91283472332";
// string s = "+-12";
// string s = "";
// string s = "+";
// string s = " +0 123";
// string s = "words and 987";
string s = " -11919730356x";
sol.myAtoi(s);
return 0;
}