题目链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
题目如下:
class Solution {
public int evalRPN(String[] tokens) {
//tip:
//1、Java中的栈的定义及使用,其中pop()是弹出并返回元素值,peek()是返回值但不弹出
//2、string转为一个字符数组:char[] toCharArray();
//3、string转成一个整数:
// 方法一:String s="123456";
// int b=Integer.parseInt(s);
// 方法二:String s="123456";
// int c=Integer.valueOf(s);
Stack<Integer> stacknum=new Stack<Integer>();
int num=0;
char ch=' ';
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")) ch='+';
else if(tokens[i].equals("-")) ch='-';
else if(tokens[i].equals("*")) ch='*';
else if(tokens[i].equals("/")) ch='/';
else stacknum.push(Integer.parseInt(tokens[i]));
if(ch!=' '){
int b=stacknum.pop();//此处要留意,入栈出栈顺序,是a-b而不是b-a
int a=stacknum.pop();
switch(ch){
case '+': num=a+b;break;
case '-': num=a-b;break;
case '*': num=a*b;break;
case '/': num=a/b;break;
}
ch=' ';
stacknum.push(num);
System.out.println(num);
}
}
return stacknum.pop();
}
}