-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008-string-to-integer-atoi.cpp
More file actions
98 lines (88 loc) · 3.15 KB
/
0008-string-to-integer-atoi.cpp
File metadata and controls
98 lines (88 loc) · 3.15 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
#include <climits>
#include <exception>
#include <functional>
#include <iostream>
#include <string>
#include <map>
#include <vector>
class AutomationEndException: public std::exception {
public:
const char * what() const noexcept override {
return "End of Automation";
};
};
class Automation {
private:
bool positive_sign;
long value;
std::string state;
std::map<std::string, std::vector<std::string>> trsfer_table;
public:
Automation():positive_sign(true), value(0), state("start"){
// 点 --线--> 点
// 状态:start、signed、in_number、end
// 输入情况:' '、 +/-、number、other
// 触发迁移表: 状态 * 情况
// ' '、 +/-、 number、 other
this->trsfer_table["start"] = {"start", "signed", "in_number", "end"};
this->trsfer_table["signed"] = {"end", "end", "in_number", "end"};
this->trsfer_table["in_number"] = {"end", "end", "in_number", "end"};
this->trsfer_table["end"] = {"end", "end", "end", "end"};
}
int get_state_column(char c) {
int column_index = 3;
if (std::isdigit(c)) {
column_index = 2;
}
else if (std::isblank(c)) {
column_index = 0;
}else if ('+' == c or '-' == c) {
column_index = 1;
}
return column_index;
}
void transfer(char c) {
this->state = this->trsfer_table[this->state][this->get_state_column(c)];
if (this->state == "in_number") {
this->value = this->value * 10 + (c - '0');
if ((-1 + 2 * this->positive_sign) * this->value >= INT_MAX) {
this->positive_sign = true;
this->value = INT_MAX;
throw AutomationEndException();
}else if ( (-1 + 2 * this->positive_sign) * this->value <= INT_MIN) {
this->positive_sign = true;
this->value = INT_MIN;
throw AutomationEndException();
}
}
else if (this->state == "signed") {
this->positive_sign = c == '+' ? true: false;
}else if (this->state == "end") {
throw AutomationEndException();
}
}
int get_result(){
return this->positive_sign ? this->value : -1 * this->value;
}
};
class Solution {
public:
int myAtoi(std::string s) {
// 状态机实现反而没有直接处理好
Automation automation = Automation();
for (auto c: s){
try {
automation.transfer(c);
} catch (AutomationEndException ae) {
std::cout<<ae.what()<<std::endl;
break;
}
};
return automation.get_result();
}
};
int main(int argc, char const *argv[]) {
std::cout<<Solution().myAtoi("-91283472332")<<std::endl;
std::cout<<Solution().myAtoi("2147483648")<<std::endl;
return 0;
}