(leetcode)Evaluate Reverse Polish Notation

来源:互联网 发布:三线性优化各向异性 编辑:程序博客网 时间:2024/06/08 16:48

Question:

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> temp;    int sum = 0;    int  op1,op2,op3;    for(int i =0;i < tokens.size();i++)    {        if(tokens[i]!= "\0")        {            if((tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")&&temp.size()>=2)            {                op2 = temp.top();temp.pop();                op1 = temp.top();temp.pop();                op3 = op(op1,op2,tokens[i][0]);                temp.push(op3);            }            else                temp.push(stoi(tokens[i]));        }    }    return temp.top();}int op(int op1,int op2,char op){    switch(op)    {        case '+':return op1+op2;        case '-': return op1-op2;        case '*': return op1*op2;        case '/':        if(op2!=0)        return op1/op2;        else        printf("error!\n");    }}};


已AC。

0 0