博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
150. Evaluate Reverse Polish Notation
阅读量:7236 次
发布时间:2019-06-29

本文共 1944 字,大约阅读时间需要 6 分钟。

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:

Input: ["2", "1", "+", "3", "*"]Output: 9Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]Output: 6Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]Output: 22Explanation:   ((10 * (6 / ((9 + 3) * -11))) + 17) + 5= ((10 * (6 / (12 * -11))) + 17) + 5= ((10 * (6 / -132)) + 17) + 5= ((10 * 0) + 17) + 5= (0 + 17) + 5= 17 + 5= 22

难度:medium

题目:

求算术表达式在反波兰表示法中的值。
有效的操作符是+、-、*、/。每个操作数可以是一个整数或另一个表达式。

思路:栈

Runtime: 6 ms, faster than 91.00% of Java online submissions for Evaluate Reverse Polish Notation.

Memory Usage: 36.6 MB, less than 100.00% of Java online submissions for Evaluate Reverse Polish Notation.

class Solution {    public int evalRPN(String[] tokens) {        Stack
stack = new Stack<>(); int tNum = 0; for (int i = 0; i < tokens.length; i++) { switch(tokens[i]) { case "+" : stack.push(stack.pop() + stack.pop()); break; case "-" : tNum = stack.pop(); stack.push(stack.pop() - tNum); break; case "*" : stack.push(stack.pop() * stack.pop()); break; case "/" : tNum = stack.pop(); stack.push(stack.pop() / tNum); break; default : stack.push(Integer.parseInt(tokens[i])); } } return stack.pop(); }}

转载地址:http://pvgfm.baihongyu.com/

你可能感兴趣的文章
动态SQL番外篇
查看>>
项目中数据库超时设置整理
查看>>
boot和settlement日志在不断加大,需要清理
查看>>
mysql #1062 – Duplicate entry '1′ for key ‘PRIMARY'
查看>>
【转载】小小的公共库,大大的耦合,你痛过吗?
查看>>
图的遍历(深度优先搜索法和广度优先搜索法)
查看>>
在线更新问题 HDU5877 线段树
查看>>
[转] 深入浅出mongoose-----包括mongoose基本所有操作,非常实用!!!!!
查看>>
CSS创建三角形(小三角)的几种方法
查看>>
Python简单基础小程序
查看>>
Python 购物车练习 2.0
查看>>
Hdoj 4089
查看>>
mikadonic-03-NIS+NFS+Autofs
查看>>
CSS单位解释.
查看>>
JAVA进阶18
查看>>
转 如何在secureCRT上设置常用的快捷输出按钮栏听语音
查看>>
转 Docker Swarm vs Kubernetes
查看>>
47-使用列表进行模拟栈
查看>>
Myisam和innodb 和memory的区别
查看>>
.Net 特性 attribute 学习 ----自定义特性
查看>>