逆波蘭表達式的求值問題

題目描述

根據逆波蘭表示法,求表達式的值。
有效的運算符包括 +, -, *, / 。每個運算對象可以是整數,也可以是另一個逆波蘭表達式。

算法思想

遍歷字符串,若爲數字就入棧,若爲運算符,則將數字出棧進行運算

Java代碼

public int evalRPN(String[] tokens) {
        Stack<Integer> s = new Stack<>();
        int a , b;
        for(String str : tokens){
            if(str.equals("+")){
                s.push(s.pop() + s.pop());
            }else if(str.equals("-")){
                b = s.pop();
                a = s.pop();
                s.push(a - b);
            }else if(str.equals("*")){
                s.push(s.pop() * s.pop());
            }else if(str.equals("/")){
                b = s.pop();
                a = s.pop();
                s.push(a / b);
            }else{
                try{
                    int num = Integer.parseInt(str);
                    s.push(num);
                }catch(NumberFormatException e){
                    e.printStackTrace();
                }
            }
        }
        return s.pop();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章