2、evaluate-reverse-polish-notation

时间:2023-03-09 22:02:01
2、evaluate-reverse-polish-notation

题目描述

Evaluate the value of an arithmetic expression in Reverse
Polish Notation
.

Valid operators are+,-,*,/. Each operand may be an integer or
another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

//判断字符串是否是数字,如果是就压栈,不是就弹出2个元素进行计算,将计算结果压栈

//最后栈顶元素即为所求
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for (int i = ; i < tokens.size(); i++){
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int temp = ;
int a = st.top();
st.pop();
int b = st.top();
st.pop();
if (tokens[i] == "+") { temp = b + a; }
else if (tokens[i] == "-") { temp = b - a; }
else if (tokens[i] == "*") { temp = b * a; }
else { temp = b / a; }
st.push(temp);
}
else {
st.push(stoi(tokens[i]));
}
}
return st.top();
}
};