本人电子系,只为一学生。心喜计算机,小编以怡情。
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
注意负数的处理,比较麻烦
static public int evalRPN(String[] tokens) {
// Write your code here
Stack<String> sta=new Stack<String>();
for (int i = 0; i < tokens.length; i++) {
if((tokens[i].startsWith("-")&&tokens[i].length()!=1)||Character.isDigit(tokens[i].charAt(0)))
{
sta.push(tokens[i]);
}
else
{
int a=0;
int b=0;
String temp1=sta.pop();
String temp2=sta.pop();
if(temp1.startsWith("-"))
{
a=(-1)*Integer.parseInt(temp1.substring(1,temp1.length()));
}
else
a=Integer.parseInt(temp1);
if(temp2.startsWith("-"))
{
b=(-1)*Integer.parseInt(temp2.substring(1,temp2.length()));
}
else
b=Integer.parseInt(temp2);
sta.push(String.valueOf(caculate(a,b,tokens[i])));
}
}
return Integer.parseInt(sta.pop());
}
static public int caculate(int a,int b,String op)
{
if(op.equals("+")){return a+b;}
if(op.equals("-")){return b-a;}
if(op.equals("*")){return a*b;}
{return b/a;}
}