题目
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
思路
遇到字符,直接出栈两个数,然后把这个结果入栈
注意转化字符串和数字的方法
String s = '123';
//字符串转化为int
int i = Integer.parseInt(s);
//字符串转化为float, double
Float f = Float.parseFloat(s);
Double d = Double.parseDouble(s);
//字符串转化为boolean
boolean b = Boolean.parseBoolean(s);
//数字转化为字符串
String s = String.valueOf(value);
代码
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s: tokens){
if ( s.equals("+")){
int a = stack.pop();
int b = stack.pop();
stack.add(a + b);
}else if (s.equals("-")){
int a = stack.pop();
int b = stack.pop();
stack.add(b - a);
}else if (s.equals("*")){
int a = stack.pop();
int b = stack.pop();
stack.add(a * b);
}else if (s.equals("/")){
int a = stack.pop();
int b = stack.pop();
stack.add(b / a);
}else{
stack.add(Integer.parseInt(s));
}
}
return stack.pop();
}
}