首页 > 其他 > 详细

华为机试题:仿LISP

时间:2019-08-04 10:15:48      阅读:174      评论:0      收藏:0      [点我收藏+]
package com.nowcoder.huawei;

import java.util.*;

public class LISP {
    // 只通过80%
    // (+ (* 2 3) (^ 4))
    // (+ (* 2 3) (^ 4))(2 3)
    // ((+ 2 3)
    // ((+ 2 3))
    // (^ (+ (* 2 3) (^ ((^ 4)))))
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String express = scanner.nextLine();

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < express.length(); i++) {
            char c = express.charAt(i);
            if (c == ‘)‘) {
                StringBuilder builder = new StringBuilder();
                char top;
                while (!stack.empty() &&(top = stack.pop()) != ‘(‘) {
                    builder.append(top);
                }

                String currExp = builder.reverse().toString();
//                System.out.println(currExp);

                String[] ops = currExp.split(" ");
                if (ops.length == 2) {
                    int value = Integer.valueOf(ops[1]);
                    value++;
                    String count = String.valueOf(value);
                    for (int j = 0; j < count.length(); j++) {
                        stack.push(count.charAt(j));
                    }
                } else if (ops.length == 3) {
                    int a = Integer.valueOf(ops[1]);
                    int b = Integer.valueOf(ops[2]);
                    int value = 0;
                    switch (ops[0]) {
                        case "+":
                            value = a + b;
                            break;
                        case "*":
                            value = a * b;
                            break;
                    }
                    String count = String.valueOf(value);
                    for (int j = 0; j < count.length(); j++) {
                        stack.push(count.charAt(j));
                    }
                } else if (ops.length == 1) {
                    for (int j = 0; j < ops[0].length(); j++) {
                        stack.push(ops[0].charAt(j));
                    }
                }

            } else {
                stack.push(c);
            }
        }

        StringBuilder builder = new StringBuilder();
        while (!stack.empty())
            builder.append(stack.pop());

        try {
            System.out.println(Integer.valueOf(builder.reverse().toString()));
        } catch (Exception e) {
            System.out.println(-1);
        }
    }
}

 

华为机试题:仿LISP

原文:https://www.cnblogs.com/bigdata-stone/p/11297179.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!