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

    Evaluate 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


    c++版本:
    class Solution{
    public:
        int evalRPN(vector<string> &tokens){
            if(tokens.size()==1)
                return stoi(*tokens.begin());
            stack<int> numbers;
            vector<string>::iterator it=tokens.begin();
            int op1=0;
            int op2=0;
            while(it!=tokens.end()){
                    if(*it=="+"||*it=="-"||*it=="*"||*it=="/"){
                        op2=numbers.top();
                        numbers.pop();
                        op1=numbers.top();
                        numbers.pop();
                        if(*it=="+")  numbers.push(op1+op2);
                        else if(*it=="-") numbers.push(op1-op2);
                        else if(*it=="*") numbers.push(op1*op2);
                        else              numbers.push(op1/op2);
                    }
                    else
                        numbers.push(stoi(*it));
                        it++;
                }
                    return numbers.top();}
    
    };
    

      Java版本:

    public class Solution {
        public int evalRPN(String[] tokens) {
            int returnValue = 0;
            String operators = "+-*/";
            Stack<String> stack = new Stack<String>();
            for(String t:tokens) {
                if(!operators.contains(t)) {
                    stack.push(t);
                } else {
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());
                    int index = operators.indexOf(t);
                      switch(index){
                          case 0:
                              stack.push(String.valueOf(a+b));
                              break;
                          case 1:
                              stack.push(String.valueOf(b-a));
                              break;
                          case 2:
                              stack.push(String.valueOf(a*b));
                              break;
                          case 3:
                              stack.push(String.valueOf(b/a));
                              break;
                      }
                }
            }
            returnValue = Integer.valueOf(stack.pop());
            return returnValue;
        }
    }
  • 相关阅读:
    Docker 系列(九):docker-compose
    Docker实践:部署Mysql
    Linux 查看端口占用情况
    Docker实践:部署Rabbitmq容器
    VS遇到的一些问题及解决办法(持续更新)
    vue-cli2.0引入nprogress 进度条
    ElmentUI全局禁止点击遮罩层关闭el-dialog弹窗
    mongodb基础教程
    C# Socket网络编程精华篇
    MySQL 日期计算
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4035497.html
Copyright © 2011-2022 走看看