package Stack;
import java.util.Stack;
public class EvalRPN_150 {
/*
* 根據逆波蘭表示法,求表達式的值。
*
* 有效的運算符包括 +, -, *, / 。每個運算對象可以是整數,也可以是另一個逆波蘭表達式。
*
* 說明:
*
* 整數除法只保留整數部分。 給定逆波蘭表達式總是有效的。換句話說,表達式總會得出有效數值且不存在除數爲 0 的情況。
*
* 示例 1:
*
* 輸入: ["2", "1", "+", "3", "*"] 輸出: 9 解釋: ((2 + 1) * 3) = 9
*
* 示例 2:
*
* 輸入: ["4", "13", "5", "/", "+"] 輸出: 6 解釋: (4 + (13 / 5)) = 6
*
* 示例 3:
*
* 輸入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] 輸出:
* 22 解釋: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) +
* 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 =
* 17 + 5 = 22
*
* 來源:力扣(LeetCode)
* 鏈接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
* 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
*/
public static void main(String[] args) {
System.out.println();
}
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for (String s : tokens) {
if ("+".equals(s)) {
int k2=Integer.parseInt(stack.pop());
int k1=Integer.parseInt(stack.pop());
Integer res=k1+k2;
stack.push(res.toString());
} else if ("-".equals(s)) {
int k2=Integer.parseInt(stack.pop());
int k1=Integer.parseInt(stack.pop());
Integer res=k1-k2;
stack.push(res.toString());
} else if ("*".equals(s)) {
int k2=Integer.parseInt(stack.pop());
int k1=Integer.parseInt(stack.pop());
Integer res=k1*k2;
stack.push(res.toString());
} else if ("/".equals(s)) {
int k2=Integer.parseInt(stack.pop());
int k1=Integer.parseInt(stack.pop());
Integer res=k1/k2;
stack.push(res.toString());
} else {
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}
150. 逆波蘭表達式求值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.