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;
        }
    }
  • 相关阅读:
    关于oracle小数和整数混合排序错误问题
    oracle 格式转换 <行转列列转行>
    Postgresql 配置文件详解
    Postgresql 同步流复制
    Postgresql 安装
    mongodb 复制集 维护小结
    mongodb 角色总结
    mongodb 安全认证
    SqlServer实时数据同步到mysql
    批量修改在索引中增加字段
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4035497.html
Copyright © 2011-2022 走看看