博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[算法]Evaluate Reverse Polish Notation
阅读量:4982 次
发布时间:2019-06-12

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

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. For example:

 

1. Naive Approach

This problem can be solved by using a stack. We can loop through each element in the given array. When it is a number, push it to the stack. When it is an operator, pop two numbers from the stack, do the calculation, and push back the result.

 
public class Test {
 
public static void main(String[] args) throws IOException {
String[] tokens = new String[] { "2", "1", "+", "3", "*" };
System.out.println(evalRPN(tokens));
}
 
public static int evalRPN(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
 
Stack
stack = new Stack
();
 
for (String t : tokens) {
if (!operators.contains(t)) { //push to stack if it is a number
stack.push(t);
} else {
//pop numbers from stack if it is an operator
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch (t) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}
 
returnValue = Integer.valueOf(stack.pop());
 
return returnValue;
}
}

or

 
public class Solution {
public int evalRPN(String[] tokens) {
 
int returnValue = 0;
 
String operators = "+-*/";
 
Stack
stack = new Stack
();
 
for(String t : tokens){
if(!operators.contains(t)){
stack.push(t);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}
}
 
returnValue = Integer.valueOf(stack.pop());
 
return returnValue;
 
}
}

转载于:https://www.cnblogs.com/xiaomoxian/p/5201731.html

你可能感兴趣的文章
Maven学习笔记(一)
查看>>
分割线
查看>>
xls的读写
查看>>
用函数创建子进程
查看>>
Myeclipse配置插件
查看>>
gitlab配置通过smtp发送邮件(QQ exmail腾讯企业为例)
查看>>
蓝桥杯之入学考试
查看>>
新公司java的注解以及springboot的相关注解
查看>>
Unity脚本的生命周期中几个重要的方法
查看>>
poj1552
查看>>
Thinkphp中文水印和图片水印合体集成插件
查看>>
FLASK安装--兼收EZ_INSTALL及PIP
查看>>
C++静态成员变量和静态成员函数小结
查看>>
Python---Flask--02--模板
查看>>
PHP学习笔记---封装(面向对象三大特性之一)
查看>>
如何快速找到指定端口被哪个程序占用并释放该端口(解决bindException)
查看>>
迭代之while循环(1)
查看>>
final修饰的类有什么特点
查看>>
关于string类中find函数的讲解
查看>>
程序员的情书
查看>>