zoukankan      html  css  js  c++  java
  • 栈计算问题

    题意是给一组数字+符号(自增1:^,相乘*,相加+)和一个长度为16的stack。栈空取数返回-1,栈满推数返回-2。

    输入样例是1 1 + 2 ^ 3 * 这样子,做的时候紧张忽略了空格,用char处理的,结果炸了,只过了40%,因为那时候只有3分钟了。结束后猛然发现。代码应该是这样的。

    import java.util.Scanner;
    import java.util.Stack;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String line = in.nextLine();
            if (line != null && !line.isEmpty()) {
                int res = resolve(line.trim());
                System.out.println(String.valueOf(res));
            }
        }
    
        // write your code here
        public static int resolve(String expr) {
            Stack<Integer> stack = new Stack<>();
            String[] patterns = expr.split(" ");
            for (String pattern : patterns) {
                if (pattern.equals("*")) {
                    if (stack.size() < 2) return -1;
                    stack.push(stack.pop() * stack.pop());
                } else if (pattern.equals("+")) {
                    if (stack.size() < 2) return -1;
                    stack.push(stack.pop() + stack.pop());
                } else if (pattern.equals("^")) {
                    if (stack.isEmpty()) return -1;
                    Integer integer = stack.pop();
                    stack.push(++integer);
                } else {
                    if (stack.size() >= 16) return -2;
                    stack.push(Integer.parseInt(pattern));
                }
            }
            return stack.pop();
        }
    }
    
  • 相关阅读:
    201275判断joomla首页的方法
    phpcms添加视频模块(未完)
    Joomla学习总结
    Joomla资源
    2012725 K2组件学习
    Apache Commons configuration使用入门
    linux学习(7)压缩与解压缩
    linux学习(6)redhat安装xwindow环境
    linux学习(5)iptables防火墙设置
    java实现的一个分页算法
  • 原文地址:https://www.cnblogs.com/cielosun/p/6771275.html
Copyright © 2011-2022 走看看