题解 | 四则运算

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        System.out.println(calculate(s));
    }

    public static int calculate(String s) {
        Stack<Integer> num = new Stack<>(); //数字栈
        Stack<Character> oper = new Stack<>(); //符号栈
        // 3+2*{1+2*[-4/(8-6)+7]}
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
                oper.push(s.charAt(i));
            } else if (s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}') {
                while (oper.peek() != '(' && oper.peek() != '[' && oper.peek() != '{') {
                    num.push(calc(num.pop(), num.pop(), oper.pop()));
                }
                oper.pop();
            } else if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' ||
                       s.charAt(i) == '/') {
                while (!oper.isEmpty() &&
                        getPriority(oper.peek()) >= getPriority(s.charAt(i))) {
                    num.push(calc(num.pop(), num.pop(), oper.pop()));
                }
                //负数处理
                if (s.charAt(i) == '-' && (i == 0 || s.charAt(i - 1) == '(' ||
                                           s.charAt(i - 1) == '[' || s.charAt(i - 1) == '{')) {
                    num.push(-1 * (s.charAt(i + 1) - '0'));
                    i++;
                    continue;
                }
                oper.push(s.charAt(i));
            } else {
                //读取到完整数字
                int num1 = 0;
                while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                    num1 = num1 * 10 + (s.charAt(i) - '0');
                    i++;
                }
                i--;
                num.push(num1);
            }
        }
        while (!oper.isEmpty()) {
            num.push(calc(num.pop(), num.pop(), oper.pop()));
        }
        return num.pop();
    }

    public static int calc(int b, int a, char oper) {
        if (oper == '+') return a + b;
        else if (oper == '-') return a - b;
        else if (oper == '*') return a * b;
        else return a / b;
    }

    public static int getPriority(char oper) {
        if (oper == '+' || oper == '-') return 1;
        else if (oper == '*' || oper == '/') return 2;
        else return 0;
    }
}

学习中缀表达式解四则运算,主要是注意负数的处理和多位数字的处理

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务