• 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();
            
        }
    }

  • 相关阅读:
    STM32的GPIO工作原理 | 附电路图详细分析
    话说上拉电阻和下拉电阻
    Linux下MySQL数据库常用基本操作
    Linux acpi off学习的必要
    CentOS 6.2出现Disk sda contains BIOS RAID metadata解决方法
    降低开关电源纹波的三个要素
    什么是RFID? 射频识别技术的特点及工作原理!
    亲测可用的国内maven镜像
    Linux 删除文件夹和文件的命令
    [Gradle] 在 Eclipse 下利用 gradle 构建系统
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5499466.html
Copyright © 2020-2023  润新知