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
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
vector<string> ::iterator it = tokens.begin();
int num1 = 0,num2 = 0;
while(it != tokens.end()){
if(*it == "+"||*it == "-" || *it == "*" || *it == "/"){
num2 = s.top();
s.pop();
num1 = s.top();
s.pop();
if(*it == "+")
s.push(num1 + num2);
if(*it == "-")
s.push(num1 - num2);
if(*it == "*")
s.push(num1 * num2);
if(*it == "/")
s.push(num1 / num2);
}
else
s.push(stoi(*it));
it ++;
}
return s.top();
}
};
本文介绍了一种使用栈的数据结构来解析并计算逆波兰表示法(Reverse Polish Notation, RPN)算术表达式的算法实现。通过遍历输入的字符串数组,遇到操作数则压入栈中,遇到运算符则从栈顶取出两个操作数进行计算,并将结果再次压入栈中,直至遍历结束,栈顶元素即为表达式的计算结果。
308

被折叠的 条评论
为什么被折叠?



