Skip to content

Commit f54adee

Browse files
committed
refactory the code
1 parent 9dd87d4 commit f54adee

File tree

1 file changed

+31
-36
lines changed

1 file changed

+31
-36
lines changed

‎algorithms/cpp/evaluateReversePolishNotation/evaluateReversePolishNotation.cpp

+31-36
Original file line numberDiff line numberDiff line change
@@ -26,61 +26,56 @@ using namespace std;
2626

2727

2828
class Solution {
29-
#define ERROR err=false;continue
3029
public:
3130
int evalRPN(vector<string> &tokens) {
3231
int i =0;
3332
bool err = false;
3433
vector<int> exp;
3534
for (int i=0; i<tokens.size() && !err; i++ ){
36-
if( isOp(tokens[i])==true ) {
37-
if (exp.size() >= 2) {
38-
int lhs, rhs;
39-
rhs = exp.back();
40-
exp.pop_back();
41-
lhs = exp.back();
42-
exp.pop_back();
43-
44-
int evlValue;
45-
if (tokens[i]=="+"){
46-
evlValue = lhs + rhs;
47-
}else if (tokens[i]=="-"){
48-
evlValue = lhs - rhs;
49-
}else if (tokens[i]=="*"){
50-
evlValue = lhs * rhs;
51-
}else if (tokens[i]=="/"){
52-
evlValue = lhs / rhs;
53-
}
54-
55-
exp.push_back(evlValue);
56-
57-
}else{
58-
ERROR;
59-
}
60-
}else if (isNum(tokens[i])) {
35+
if (isNum(tokens[i])) {
6136
exp.push_back(value);
37+
} else if( isOp(tokens[i])==true ) {
38+
if (exp.size() < 2) {
39+
return 0; //ERROR
40+
}
41+
int lhs, rhs;
42+
rhs = exp.back();
43+
exp.pop_back();
44+
lhs = exp.back();
45+
exp.pop_back();
46+
47+
int evlValue;
48+
if (tokens[i]=="+"){
49+
evlValue = lhs + rhs;
50+
}else if (tokens[i]=="-"){
51+
evlValue = lhs - rhs;
52+
}else if (tokens[i]=="*"){
53+
evlValue = lhs * rhs;
54+
}else if (tokens[i]=="/"){
55+
evlValue = lhs / rhs;
56+
}
57+
58+
exp.push_back(evlValue);
59+
6260
}else {
63-
ERROR;
61+
return 0; //ERROR
6462
}
6563
}
66-
if (err==true){
67-
return 0;
68-
}
69-
64+
7065
if (exp.size()==1){
7166
return exp.back();
7267
}
7368
return 0;
74-
69+
7570
}
76-
71+
7772
private:
7873
long value;
79-
74+
8075
bool isOp(string &op) {
8176
return (op=="+" || op=="-" || op=="*" || op=="/");
8277
}
83-
78+
8479
bool isNum(string &num) {
8580
char *end;
8681
value = strtol(num.c_str(), &end, 10);
@@ -97,7 +92,7 @@ int main()
9792
Solution s;
9893
char exps[5][3] = {"42", "9", "6", "-", "+"};
9994
vector<string> expression;
100-
95+
10196
cout << "Expression: \n ";
10297
for (int i=0; i<5; i++){
10398
expression.push_back(exps[i]);

0 commit comments

Comments
 (0)