首页 > 代码库 > Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation
Evaluate 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
c++版本:
class Solution{public: int evalRPN(vector<string> &tokens){ if(tokens.size()==1) return stoi(*tokens.begin()); stack<int> numbers; vector<string>::iterator it=tokens.begin(); int op1=0; int op2=0; while(it!=tokens.end()){ if(*it=="+"||*it=="-"||*it=="*"||*it=="/"){ op2=numbers.top(); numbers.pop(); op1=numbers.top(); numbers.pop(); if(*it=="+") numbers.push(op1+op2); else if(*it=="-") numbers.push(op1-op2); else if(*it=="*") numbers.push(op1*op2); else numbers.push(op1/op2); } else numbers.push(stoi(*it)); it++; } return numbers.top();}};
Java版本:
public class Solution { public int evalRPN(String[] tokens) { int returnValue = http://www.mamicode.com/0; String operators = "+-*/"; Stack<String> stack = new Stack<String>(); for(String t:tokens) { if(!operators.contains(t)) { stack.push(t); } else { int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); int index = operators.indexOf(t); switch(index){ case 0: stack.push(String.valueOf(a+b)); break; case 1: stack.push(String.valueOf(b-a)); break; case 2: stack.push(String.valueOf(a*b)); break; case 3: stack.push(String.valueOf(b/a)); break; } } } returnValue = Integer.valueOf(stack.pop()); return returnValue; }}
Evaluate Reverse Polish Notation
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。