您的位置:首页 > 编程语言 > Lua

LeetCode 150 Evaluate Reverse Polish Notation

2014-06-20 22:41 169 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are
+
,
-
,
*
,
/
. Each operand may be an integer or another expression.Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
public class Solution {
	public int evalRPN(String[] tokens) {
		int num1, num2, temp;
		Stack<Integer> sk = new Stack<Integer>();
		for (String str : tokens) {
			if (str.equals("+")) {
				num1 = sk.pop();
				num2 = sk.pop();
				temp = num2 + num1;
			} else if (str.equals("-")) {
				num1 = sk.pop();
				num2 = sk.pop();
				temp = num2 - num1;
			} else if (str.equals("/")) {
				num1 = sk.pop();
				num2 = sk.pop();
				temp = num2 / num1;
			} else if (str.equals("*")) {
				num1 = sk.pop();
				num2 = sk.pop();
				temp = num2 * num1;
			} else
				temp = Integer.parseInt(str);
			sk.push(temp);
		}
		return sk.pop();
	}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: