-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc8.cpp
More file actions
95 lines (72 loc) · 1.76 KB
/
lc8.cpp
File metadata and controls
95 lines (72 loc) · 1.76 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
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
int myAtoi(string s) {
int i = 0;
bool neg = false;
string d = "";
if (s.empty()) return 0;
while (isspace(s[i])) i++;
if (i >= s.size()) return 0;
if (s[i] == '-') {
neg = true;
i++;
} else if (s[i] == '+') {
i++;
}
if (i >= s.size() || !isdigit(s[i])) {
return 0;
}
while (isdigit(s[i])) {
d += s[i++];
}
if (d.empty())
return 0;
i = 0;
while (d[i] == '0')
i++;
d.erase(0, i);
if (d.empty())
return 0;
long long result = 0;
for (int i = 0; i < d.size(); i++) {
if (result > (INT_MAX - (d[i] - '0')) / 10) {
return neg ? INT_MIN : INT_MAX;
}
result = result * 10 + (d[i] - '0');
}
if (result > INT_MAX) {
return neg ? INT_MIN : INT_MAX;
}
if (neg) {
result = -result;
}
return result;;
}
};
int main(int argc, char **argv) {
Solution *sol = new Solution();
vector<string> testCases = {
" -042",
"-91283472332",
" +42",
" -42abc",
"abc123",
"-00000000000000123abc",
" + 42",
"-2147483648",
"0-1",
"1337c0d3",
"words and 987"
};
for(int i = 0; i < testCases.size(); i++) {
cout << testCases[i] << " ";
int result = sol->myAtoi(testCases[i]);
cout << result << endl;
}
return 0;
}