[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();}
阅读全文
0 0
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- Java中的String和String pool
- **洛谷P1028 数的计算(NOIp2001)
- java 虚拟机 类加载
- 整数排序 II
- 1.整洁代码
- [LeetCode]Evaluate Reverse Polish Notation
- vb.net 教程 11-1 打印组件 4 PrintDocument 3
- 技术| Android ConstraintLayout初级使用记录
- 创建模式之一 ---工厂模式
- Docker容器的重启策略及docker run的--restart选项详解
- android 页面下拉刷新,添加新数据
- HTML5中Audio标签ended属性的使用
- 树莓派学习二(点亮LED灯)
- seo/sem简单记忆