import java.util.Stack;
public class Solution {
//逆波兰式求解多项式计算
public int evalRPN(String[] tokens) {
if(tokens==null)
return 0;
if(tokens.length==1&&tokens[0]!="+"
&&tokens[0]!="-"&&tokens[0]!="*"&&tokens[0]!="/")
return Integer.parseInt(tokens[0]);
Stack<Integer>stack=new Stack<Integer>();
stack.push(Integer.parseInt(tokens[0]));
stack.push(Integer.parseInt(tokens[1]));
int temp1=0;
int temp2=0;
for(int i=2;i!=tokens.length;i++)
{
if(tokens[i].equals("+"))
{
temp1=stack.pop();
temp2=stack.pop();
stack.push(temp1+temp2);
}else if(tokens[i].equals("-"))
{
temp1=stack.pop();
temp2=stack.pop();
stack.push(temp2-temp1);
}else if(tokens[i].equals("*"))
{
temp1=stack.pop();
temp2=stack.pop();
stack.push(temp1*temp2);
}else if(tokens[i].equals("/"))
{
temp1=stack.pop();
temp2=stack.pop();
if(temp1==0||temp2==0)
{
stack.push(0);
}else{
stack.push(temp2/temp1);
}
}else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
//方法二:运用try-catch计算公式
public int evalRPN2(String[] tokens) {
if(tokens==null)
return 0;
if(tokens.length==1&&tokens[0]!="+"
&&tokens[0]!="-"&&tokens[0]!="*"&&tokens[0]!="/")
return Integer.parseInt(tokens[0]);
Stack<Integer>stack=new Stack<Integer>();
int a=0;
int b=0;
for(int i=0;i!=tokens.length;i++)
{
try{
stack.add(Integer.parseInt(tokens[i]));
}catch(Exception e){
b=stack.pop();
a=stack.pop();
stack.push(compute(a,b,tokens[i]));
}
}
return stack.pop();
}
public int compute(int a,int b,String operator)
{
switch (operator)
{
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
public static void main(String[]args){
//System.out.println("Hello");
//String[]tokens={"2","1","+","3","*"};
String[]tokens={"4","3","-"};
Solution s=new Solution();
System.out.println(s.evalRPN2(tokens));
}
}
逆波兰式求解多项式
猜你喜欢
转载自blog.csdn.net/u012017783/article/details/80499105
今日推荐
周排行