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;
        }
    }
  • 相关阅读:
    Python数组操作将一维数组变成二维数组
    Python做一个计时器的动画
    tkinter添加背景音乐
    IDEA——配置代码检测
    Jenkins构建 前端node项目
    linux下python相关命令
    推荐几个IT交流社区
    jenkins常用插件
    linux上安装newman
    linux+jenkins+postman持续集成
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4035497.html
Copyright © 2011-2022 走看看