一,给一个逆波兰式的公式,求出它的值
1, 该公式运算符只有^, + ,* 这三个,其中^表示自增的。
2,例如输入: 1 1 + 2 ^ *
输出为6;
二,程序
import java.util.*; //阿里的程序题
public class Test2 {
public static void main(String[] agrs) {
ArrayList<Integer> inputs = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
String line = in.nextLine();
if (line != null && !line.isEmpty()) {
int res = resolve(line.trim());
System.out.println(String.valueOf(res));
}
}
public static int resolve(String expr) {
System.out.println("expr="+expr);
ArrayList<String> strList = new ArrayList<String>();
List<String> list=new ArrayList<String>();
String str2 = "";
int flag = 0;
for (int i = 0; i < expr.length();i++)
if (Character.isDigit(expr.charAt(i))){
flag = 0;
str2 += String.valueOf(expr.charAt(i));
if (i == expr.length() - 1)
strList.add(str2);
}
else{
if (flag == 0){
strList.add(str2);
str2 = "";
flag = 1;
}
strList.add(String.valueOf(expr.charAt(i)));
}
for(int i=0;i<strList.size();i++)
{
if(!strList.get(i).equals(" "))
{
list.add(strList.get(i));
}
}
if(list.size()==0)
{
return -1;
}
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<list.size();i++)
{
if(list.get(i).equals("+")||list.get(i).equals("^")||list.get(i).equals("*"))
{
int a=stack.pop();
int c;
if(list.get(i).equals("+"))
{
int b=stack.pop();
c=a+b;
stack.push(c);
}
else if(list.get(i).equals("*"))
{
int b=stack.pop();
c=a*b;
stack.push(c);
}
else if(list.get(i).equals("^"))
{
c=a+1;
stack.push(c);
}
}
else
{
if(stack.size()<16) {
int data = Integer.parseInt(list.get(i));
stack.push(data);
// System.out.println("size="+stack.size());
}
else
{
return -1;
}
}
}
int data4=stack.pop();
return data4;
}
}