計算逆波蘭式——Leetcode系列(一)

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

My Answer:

public class Solution {
    public int evalRPN(String[] tokens) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        Integer value = new Integer(0);
        Integer temp = new Integer(0);
        for(String str : tokens){
            switch(str){
                case "+":
                    value = list.pop() + list.pop();
                    list.push(value);
                    break;
                case "-":
                    temp = list.pop();
                    value = list.pop() - temp;
                    list.push(value);
                    break;
                case "*":
                    value = list.pop() * list.pop();
                    list.push(value);
                    break;
                case "/":
                    temp = list.pop();
                    value = list.pop() / temp;
                    list.push(value);
                    break;
                default:
                    list.push(Integer.valueOf(str));
                    break;
            }
        }
        return list.pop().intValue();
    }
}

題目來源: https://oj.leetcode.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章