Evaluate Reverse Polish Notation

本文详细介绍了如何使用Java实现解析逆波兰表达式并计算其对应的算术表达式的值,包括解析过程中的操作符和操作数处理。

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:

import java.util.Scanner;
import java.util.Stack;
public class Solution {
public static int evalRPN(String[] tokens) {
	String op3="+-*/";
	Stack num= new Stack();
	int result=0;
	int index=0;
	int op=0; 
	int op2=0;
	for(int i=0;i<tokens.length;i++){
		  if(op3.contains(tokens[i])){
			    op=Integer.valueOf(num.pop().toString());
			    op2=Integer.valueOf(num.pop().toString());
			    
			    index=op3.indexOf(tokens[i]);
			   switch(index)
			   {
			   case 0:result=op2+op;num.push(result);break;
			   case 1:result=op2-op;num.push(result);break;
			   case 2:result=op*op2;num.push(result);break;
			   case 3:if(op==0)return 0;
				   result=op2/op;num.push(result);break;
		       }
	     }else{
	    	num.push(tokens[i]);
	     }
	}
	result=Integer.valueOf(num.pop().toString());
	return result;
}
     public static void main(String[] args) {
		String exp;
		String[] exp2;
		char[] ch=null;
		int result;
		Scanner scan=new Scanner(System.in);
		exp=scan.nextLine();
		exp2=exp.split(" ");
		result=evalRPN(exp2);
	   System.out.println(result);
		}
		
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值