zoukankan      html  css  js  c++  java
  • LeetCode: Evaluate Reverse Polish Notation

    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
    

    Solution:

    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> stack = new Stack<String>();
            int len = tokens.length;
            for(int i = 0;i < len;i++){
                if(tokens[i].equals("+") || tokens[i].equals("/") || tokens[i].equals("*") || tokens[i].equals("-")){
                    String b = stack.pop();  //
                    String a = stack.pop();  // 这里要注意返回的顺序
                    int result = 0;
                    if(tokens[i].equals("+")){
                         result = Integer.parseInt(a) + Integer.parseInt(b);
                    }
                    if(tokens[i].equals("/")){
                         result = Integer.parseInt(a) / Integer.parseInt(b);
                    }
                    if(tokens[i].equals("*")){
                         result = Integer.parseInt(a) * Integer.parseInt(b);
                    }
                    if(tokens[i].equals("-")){
                         result = Integer.parseInt(a) - Integer.parseInt(b);
                    }
                    String StringFormatResult = result + "";
                    stack.push(StringFormatResult);
                    
                }else{
                    stack.push(tokens[i]);
                }            
            }
            return Integer.parseInt(stack.pop());
        }
    }
  • 相关阅读:
    Java Web开发 之VO、PO、DTO等收集
    Hive的安装与使用
    各种默认回车提交表单
    A/B Problem
    A+B Problem II
    A+B Problem IV
    关于521
    劝你别做
    无主之地1
    A+B Problem(V)
  • 原文地址:https://www.cnblogs.com/yeek/p/3506030.html
Copyright © 2011-2022 走看看