计算数学表达式

题干如下:

输入一个表达式(用字符串表示),求这个表达式的值。

保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。

例如:

输入:

3+2*{1+2*[-4/(8-6)+7]}

输出:

25

思路:使用后缀表达式的方式计算,借鉴http://t.csdnimg.cn/Sv1sW

坑:负数,两位数以及往上

负数解决方案:将-2变成(0-2)的形式

多位数:很简单,遍历到一个数字的时候看它后面还有没有数字

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @className: _5_$
 * @author: Lian
 * @date: 2023-10-04 17:07
 */
public class _5_4 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Stack<Character> operator = new Stack<>();
        ArrayList<String> list = new ArrayList<>();
        Map<Character, Integer> hashMap = new HashMap<>();
        Stack<Double> stack = new Stack<>();
        hashMap.put('(', 0);
        hashMap.put('-', 1);
        hashMap.put('+', 1);
        hashMap.put('*', 2);
        hashMap.put('/', 2);
        StringBuilder str = new StringBuilder(br.readLine().replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')'));
        while (true) {
            int i;
            for (i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '-') {
                    if (i == 0 ||str.charAt(i-1)=='(') {
                        str.insert(i + 2, ")");
                        str.insert(i, "(0");
                        break;
                    }
                }
            }
            if(i==str.length())
                break;
        }

        char[] chars = str.toString().toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if (Character.isDigit(chars[i])) {
                int j = 0;
                while (i+j<chars.length&&Character.isDigit(chars[i + j])) {
                    j++;
                }
                list.add(String.copyValueOf(chars, i, j));
                i=i+j-1;
                continue;
            }
            if (chars[i] == '(') {
                operator.push(chars[i]);
                continue;
            }
            if (chars[i] == ')') {
                while (operator.peek() != '(') {
                    char c = operator.pop();
                    list.add(String.valueOf(c));
                }
                operator.pop();
                continue;
            }
            if (operator.isEmpty()) {
                operator.push(chars[i]);
                continue;
            }
            while (!operator.isEmpty() && hashMap.get(chars[i]) <= hashMap.get(operator.peek())) {
                char c = operator.pop();
                list.add(String.valueOf(c));
            }
            operator.push(chars[i]);
        }
        while (!operator.isEmpty()) {
            list.add(String.valueOf(operator.pop()));
        }

        for (int i = 0; i < list.size(); i++) {
            if (Character.isDigit(list.get(i).charAt(0))) {
                stack.push(Double.valueOf(list.get(i)));
                continue;
            }
            double a = stack.pop();
            double b = stack.pop();
            if (list.get(i).equals("+")) {
                stack.push(a + b);
                continue;
            }
            if (list.get(i).equals("*")) {
                stack.push(a * b);
                continue;
            }
            if (list.get(i).equals("-")) {
                stack.push(b - a);
                continue;
            }
            if (list.get(i).equals("/")) {
                stack.push(b / a);
            }
        }

        System.out.printf("%.0f%n", stack.peek());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值