問題:
用反波蘭式表示算術表達式的值。
有效運算符是+,-,*,/。每個操作數可以是一個整數或另一個表達式。
一些例子:
?
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
答案:
?
?
public class Solution {public int evalRPN(String[] tokens) {Stack<String> stack = new Stack<String>();for(int i=0;i<tokens.length;i++){if(tokens[i].equals("+")){int n = Integer.parseInt(stack.pop());int m = Integer.parseInt(stack.pop());stack.push(String.valueOf(n+m));}else if(tokens[i].equals("-")){int n = Integer.parseInt(stack.pop());int m = Integer.parseInt(stack.pop());stack.push(String.valueOf(m-n));}else if(tokens[i].equals("*")){int n = Integer.parseInt(stack.pop());int m = Integer.parseInt(stack.pop());stack.push(String.valueOf(n*m));}else if(tokens[i].equals("/")){int n = Integer.parseInt(stack.pop());int m = Integer.parseInt(stack.pop());int re;if(m == 0){re = 0;}else{re = m/n;}stack.push(String.valueOf(re));}else {stack.push(tokens[i]);}}return Integer.parseInt(stack.pop());}
}
?
?
?
?
?
?
?