、
思路:很简单,就是一些基本的入栈出栈操作,关键是split(“\\s+”)这一步,\s在正则表达式中是匹配任何空白字符,包括空格、制表符、换页符等等,应为\在java中是转义符,所以要打\\
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().trim();
System.out.println(resolve(str));
}
public static int resolve(String expr) {
Stack<Integer> stack = new Stack<Integer>();
String strs[]=expr.split("\\s+");//用空格隔开
for(int i=0;i<strs.length;i++){
if(!strs[i].equals("+") && !strs[i].equals("^") && !strs[i].equals("*")){
int num = Integer.parseInt(strs[i]);
stack.push(num);
if(stack.size() > 16)
return -2;
}else{
switch (strs[i]){
case "*":
if(stack.empty())
return -1;
int numRight = stack.pop();
if(stack.empty())
return -1;
int numLeft = stack.pop();
stack.push(numLeft * numRight);
break;
case "^":
if(stack.empty())
return -1;
int num = stack.pop();
stack.push(num + 1);
break;
case "+":
if(stack.empty())
return -1;
int numRight2 = stack.pop();
if(stack.empty())
return -1;
int numLeft2 = stack.pop();
stack.push(numLeft2 + numRight2);
break;
}
}
}
if(stack.empty())return -1;
return stack.pop();
}
}