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

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

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in .

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
Java代码:

public class Solution {    public  int evalRPN(String[] tokens) {		Stack
stack = new Stack<>(); if (tokens.length == 0) return 0; for (int i = 0; i < tokens.length; i++) { if (isNum(tokens[i])) { stack.push(Integer.parseInt(tokens[i])); } else { Integer n2 = stack.pop(); Integer n1 = stack.pop(); Integer result; if (tokens[i].equals("+")) { result = n1 + n2; stack.push(result); } else if (tokens[i].equals("-")) { result = n1 - n2; stack.push(result); } else if (tokens[i].equals("*")) { result = n1 * n2; stack.push(result); } else if (tokens[i].equals("/")) { result = n1 / n2; stack.push(result); } } } return stack.pop(); } public boolean isNum(String s) { try { Integer.parseInt(s); return true; } catch (Exception e) { return false; } }}
 

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

你可能感兴趣的文章
Java8 HashMap集合解析
查看>>
自定义 select 下拉框 多选插件
查看>>
linux和windows内存布局验证
查看>>
Linux常用统计命令之wc
查看>>
fastcgi_param 详解
查看>>
搞定Java面试中的数据结构问题
查看>>
kprobe学习
查看>>
React Native(一):搭建开发环境、出Hello World
查看>>
React Native(二):属性、状态
查看>>
JSX使用总结
查看>>
React Native(四):布局(使用Flexbox)
查看>>
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>