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> myStack; int first,second,merge; for(int i=0; i<tokens.size(); i++) { if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/") { first = myStack.top(); myStack.pop(); second = myStack.top(); myStack.pop(); if(tokens[i] == "+") merge = first + second; else if(tokens[i] == "-") merge = second - first; else if(tokens[i] == "*") merge = first * second; else if(tokens[i] == "/") merge = second / first; } else { merge = atoi(tokens[i].c_str()); } myStack.push(merge); } return myStack.top(); } };
leetcode——Evaluate Reverse Polish Notation 求算式值(AC),布布扣,bubuko.com
leetcode——Evaluate Reverse Polish Notation 求算式值(AC)
原文地址:http://blog.csdn.net/dalongyes/article/details/37915463