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());
        }
    }
  • 相关阅读:
    响应式开发
    webstrom配置
    CSS水平垂直居中
    CSS3里的 转换与过渡动效
    CSS布局
    CSS定宽居中的实现方案
    Flex布局篇2
    编辑器中快速生成代码——emmet输入法
    display:flex实践加感悟
    websocket connet.js
  • 原文地址:https://www.cnblogs.com/yeek/p/3506030.html
Copyright © 2011-2022 走看看