zoukankan      html  css  js  c++  java
  • leetcode

    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
    这类计算结果题目是非常好用栈实现滴,遇到数字就将数字进栈,遇到字符就将栈中最上层的两个数出栈,然后用该运算符运算,然后再将运算结果进栈。

    package com.cn.cya.evaluatereversepolishnotation;

    import java.util.Stack;

    public class Solution {
        public int evalRPN(String[] tokens) {
     
            Stack<Integer> stack=new Stack<Integer>();
            if(tokens==null||tokens.equals(""))return 0;
            for (int i = 0; i < tokens.length; i++) {
                if(tokens[i].equals("+")){
                    int a=stack.pop();
                    int b=stack.pop();
                    stack.push(b+a);
                }else if(tokens[i].equals("-")){
                    int a=stack.pop();
                    int b=stack.pop();
                    stack.push(b-a);
                }else if(tokens[i].equals("*")){
                    int a=stack.pop();
                    int b=stack.pop();
                    stack.push(a*b);
                }else if(tokens[i].equals("/")){
                    int a=stack.pop();
                    if(a==0)return 0;
                    int b=stack.pop();
                    stack.push(b/a);
                }else {
                    int a=Integer.parseInt(tokens[i]);
                    stack.push(a);
                }
            }
            return stack.pop();
            
        }
    }

  • 相关阅读:
    IT学习 程序员 学习网址收藏
    PHP地图上的点文字标注
    php 三种文件下载的实现
    10个免费的jQuery富文本编辑器
    Docker Swarm(四)Volume 数据(挂载)持久化
    Docker Swarm(三)Service(服务)分配策略
    Docker Swarm(二)常用命令
    Docker Swarm(一)集群部署
    Linux——Shell脚本参数传递的2种方法
    Linux——系统时间、开机时间
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5499466.html
Copyright © 2011-2022 走看看