leetcode面试题2:Evaluate Reverse Polish Notation
来源:互联网 发布:北京软件退税政策 编辑:程序博客网 时间:2024/06/05 15:15
题目如下:
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意思是实现逆波兰表达式,思路是利用栈,当表达式是数字时,将数字压入栈,当表达式是运算符时,从栈中取出2个数字进行运算,将结果压入栈顶。
AC代码如下:
class Solution {public: int evalRPN(vector<string> &tokens) { stack<int>num; int left_num,right_num; if(tokens.size()) { for(int i=0;i<tokens.size();i++) { if(tokens[i]=="*") { right_num=num.top(); num.pop(); left_num=num.top(); num.pop(); num.push(left_num*right_num); } else if(tokens[i]=="/") { right_num=num.top(); num.pop(); left_num=num.top(); num.pop(); num.push(left_num/right_num); } else if(tokens[i]=="+") { right_num=num.top(); num.pop(); left_num=num.top(); num.pop(); num.push(left_num+right_num); } else if(tokens[i]=="-") { right_num=num.top(); num.pop(); left_num=num.top(); num.pop(); num.push(left_num-right_num); } else { num.push(atoi(tokens[i].c_str())); } } return num.top(); } }};
0 0
- leetcode面试题2:Evaluate Reverse Polish Notation
- LeetCode problem 2: Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation [2]
- LeetCode 2 Evaluate Reverse Polish Notation
- LeetCode 2 Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation【leetcode 2】
- 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
- LCT模版
- error: couldn't parse contents of '/Users/.../Info.plist': The data couldn’t be read because...
- 程序人生的开始
- RHCE6 Preperation (1) - change root password and network setup
- 笔记22 容器
- leetcode面试题2:Evaluate Reverse Polish Notation
- cas入门之三十二: jpa ticketregistry在实际应用的一个bug
- HDU 1785 You Are All Excellent(数学题)
- 我的开源夏令营之旅
- POJ2186 Popular Cows ,有向图, Tarjan算法
- angular provider
- 以后漫长的11年,无数次的拉手走在大街小巷
- poj-2191
- cas 入门之三十:cas 集群tomcat session组播复制