-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem0087.h
60 lines (49 loc) · 1.18 KB
/
Problem0087.h
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
//
// Created by Fengwei Zhang on 2021/5/27.
//
#ifndef ACWINGSOLUTION_PROBLEM0087_H
#define ACWINGSOLUTION_PROBLEM0087_H
#include <string>
using namespace std;
class Solution {
public:
int strToInt(const string &str) {
// 处理空字符串
int i = 0;
while (i < str.length() && str[i] == ' ') {
++i;
}
if (i == str.length()) {
return 0;
}
long result = 0;
bool is_negative = false;
// 处理先导符号
if (str[i] == '-') {
is_negative = true;
++i;
} else if (str[i] == '+') {
++i;
}
// 处理前导零
while (i < str.length() && (str[i] == '0')) {
++i;
}
while (i < str.length() && str[i] >= '0' && str[i] <= '9') {
result *= 10;
result += str[i] - '0';
++i;
}
if (is_negative) {
result = -result;
}
if (result >= INT_MAX) {
return INT_MAX;
}
if (result <= INT_MIN) {
return INT_MIN;
}
return (int) result;
}
};
#endif //ACWINGSOLUTION_PROBLEM0087_H