150. Evaluate Reverse Polish Notation
来源:互联网 发布:中国广告服务贸易数据 编辑:程序博客网 时间:2024/05/22 06:05
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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = tokens.size(); stack<int> S; for(int i = 0; i < len; i++) { if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int op2 = S.top(); S.pop(); int op1 = S.top(); S.pop(); S.push( op(op1, op2, tokens[i][0]) ); } else S.push(stoi(tokens[i])); } return S.top(); } int op(int op1, int op2, char optor) { if(optor == '+')return op1 + op2; else if(optor == '-')return op1 - op2; else if(optor == '*')return op1 * op2; else return op1 / op2; }};
0 0
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- java基础-多线程
- 第3组UI(1)-AdapterView之ListView及MVC设计模式
- IOS Storyboard中使用Segue传值
- 使用gcc的-finstrument-functions选项进行函数跟踪
- visual stdio 2015下调试c++程序一闪而过决解办法
- 150. Evaluate Reverse Polish Notation
- JVM 垃圾回收器工作原理及使用实例介绍
- java的instanceof关键字
- KEIL下分散加载文件的使用
- 分析函数调用关系图(call graph)的几种方法
- 慢慢说CSS第一天
- 将字符串转为整数
- Linux C++ 服务器端学习方法
- Java程序员常用工具类库 - 目录