Skip to content

Commit 07f857a

Browse files
committed
Create Evaluate_Reverse_Polish_Notation.cc
1 parent ae9ea88 commit 07f857a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
int evalRPN(vector<string> &tokens) {
4+
stack<int> st;
5+
int x, y;
6+
for (int i = 0; i < tokens.size(); i++) {
7+
if ((tokens[i][0] >= '0' && tokens[i][0] <= '9') || (tokens[i].length() > 1)) {
8+
x = 0;
9+
int j = 0;
10+
if (tokens[i][0] == '-') j++;
11+
for (; j < tokens[i].length(); j++)
12+
x = x * 10 + (tokens[i][j] - '0');
13+
if (tokens[i][0] == '-') x = -x;
14+
st.push(x);
15+
} else {
16+
if (st.size() < 2) return ERROR_CODE;
17+
x = st.top(), st.pop();
18+
y = st.top(), st.pop();
19+
if (tokens[i][0] == '+') st.push(x + y);
20+
else if (tokens[i][0] == '-') st.push(y - x);
21+
else if (tokens[i][0] == '*') st.push(y * x);
22+
else if (tokens[i][0] == '/' && x != 0) st.push(y / x);
23+
else return ERROR_CODE;
24+
}
25+
}
26+
return st.empty() ? 0 : st.top();
27+
}
28+
private:
29+
int ERROR_CODE = -1;
30+
};

0 commit comments

Comments
 (0)