-
Notifications
You must be signed in to change notification settings - Fork 5
/
solution.cpp
55 lines (45 loc) · 1.25 KB
/
solution.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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int myAtoi(string s) {
long long ans = 0;
// 去除前导空格
int start = 0;
while (start < s.length() && s[start] == ' ') start++;
if (start == s.length()) return 0;
// 判断正负号
int sign = 1;
if (s[start] == '-') sign = -1, start++;
else if (s[start] == '+') start++;
// 读取数字
for (int i = start; i < s.length() && isdigit(s[i]); i++) {
ans = ans * 10 + sign * (s[i] - '0');
if (ans > 0 && ans >= INT_MAX) return INT_MAX;
if (ans < 0 && ans <= INT_MIN) return INT_MIN;
}
return ans;
}
};
struct Example {
string s;
int ans;
};
int main() {
vector<Example> examples = {
{"42", 42},
{" -42", -42},
{"4193 with words", 4193},
};
Solution *solve = new Solution();
for (int i = 0; i < examples.size(); i++) {
int ans = solve->myAtoi(examples[i].s);
if (ans == examples[i].ans) {
cout << "PASS: CASE " << i << endl;
} else {
cout << "FAIL: CASE " << i << endl;
}
}
return 0;
}