-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.cpp
83 lines (74 loc) · 2.03 KB
/
main.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
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
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> operands;
vector<string>::iterator it = tokens.begin(), end = tokens.end();
int opA, opB;
while (it != end) {
if (*it == "+" || *it == "-" || *it == "*" || *it == "/") {
opB = operands.top();
operands.pop();
opA = operands.top();
operands.pop();
operands.push(cal(opA, opB, *it));
} else {
operands.push(valueOf(*it));
}
++it;
}
return operands.top();
}
private:
/** 字符串转换为相应数值 */
int valueOf(string str) {
if (str == "") return 0;
int symbol = 1, index = 0, len = str.size(), val = 0;
if (str[0] == '+') {
index = 1;
} else if (str[0] == '-') {
index = 1;
symbol = -1;
}
for (; index < len; ++index)
val = val * 10 + str[index] - '0';
return val * symbol;
}
/** 二元计算 */
int cal(int opA, int opB, string op) {
int val = 0;
switch (op[0]) {
case '+': val = opA + opB; break;
case '-': val = opA - opB; break;
case '*': val = opA * opB; break;
case '/': val = opA / opB; break;
}
return val;
}
};
int main() {
Solution s;
vector<string> tokens;
tokens.push_back("3");
tokens.push_back("1");
tokens.push_back("2");
tokens.push_back("+");
tokens.push_back("*");
cout << s.evalRPN(tokens) << endl;
tokens.clear();
tokens.push_back("2");
tokens.push_back("1");
tokens.push_back("+");
tokens.push_back("3");
tokens.push_back("*");
cout << s.evalRPN(tokens) << endl;
tokens.clear();
tokens.push_back("0");
tokens.push_back("3");
tokens.push_back("/");
cout << s.evalRPN(tokens) << endl;
return 0;
}