題目描述
根據逆波蘭表示法,求表達式的值。
有效的運算符包括 +, -, *, / 。每個運算對象可以是整數,也可以是另一個逆波蘭表達式。
算法思想
遍歷字符串,若爲數字就入棧,若爲運算符,則將數字出棧進行運算
Java代碼
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<>();
int a , b;
for(String str : tokens){
if(str.equals("+")){
s.push(s.pop() + s.pop());
}else if(str.equals("-")){
b = s.pop();
a = s.pop();
s.push(a - b);
}else if(str.equals("*")){
s.push(s.pop() * s.pop());
}else if(str.equals("/")){
b = s.pop();
a = s.pop();
s.push(a / b);
}else{
try{
int num = Integer.parseInt(str);
s.push(num);
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
return s.pop();
}