congr / world

2 stars 1 forks source link

LeetCode : 150. Evaluate Reverse Polish Notation #451

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/evaluate-reverse-polish-notation/

image image

congr commented 5 years ago
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> st = new Stack();

        for (String s : tokens) {
            if (s.equals("*")) st.push(st.pop() * st.pop());
            else if (s.equals("+")) st.push(st.pop() + st.pop());
            else if (s.equals("/")) {
                int i = st.pop();
                int j = st.pop();
                if (i == 0 || j == 0) st.push(0); // !!!
                else st.push (j/i);
            } else if (s.equals("-")) {
                int i = st.pop();
                int j = st.pop();
                st.push(j - i);    // !!!
            } else st.push(Integer.parseInt(s));
        }

        return st.pop();
    }
}