[LeetCode]Evaluate Reverse Polish Notation

来源:互联网 发布:嘟嘟牛破译软件 编辑:程序博客网 时间:2024/06/06 14:09

今天写的是Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation26.8%Medium题目描述如下:

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
要求就是翻译一个表达式,这个表达式用的是Reverse Polish Notation,每个运算符号是放在后面而不是放在中间的,要求我们计算这个表达式的结果。我们用stack来存储需要进行运算的数字,每次读取到一格运算符号时就从栈顶取出两个数进行运算,运算完毕后再将结果放入栈中。如果给定的表达式没有出错的话,那么栈里最终会只剩下一个数,而这个数就是我们想要的结果。

代码如下:

#include<cstdlib>#include<stack>int evalRPN(vector<string>& tokens) {    stack<int> nums;    for(int i=0;i<tokens.size();i++)    {        if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/")        {            nums.push(atoi(tokens[i].c_str()));        }        else if(tokens[i]=="+")        {            int a=nums.top();            nums.pop();            int b=nums.top();            nums.pop();            nums.push(a+b);        }        else if(tokens[i]=="-")        {            int a=nums.top();            nums.pop();            int b=nums.top();            nums.pop();            nums.push(b-a);        }        else if(tokens[i]=="*")        {            int a=nums.top();            nums.pop();            int b=nums.top();            nums.pop();            nums.push(a*b);        }        else if(tokens[i]=="/")        {            int a=nums.top();            nums.pop();            int b=nums.top();            nums.pop();            nums.push(b/a);        }    }        return nums.top();}


原创粉丝点击