题解 | #表达式求值#--利用栈及遍历字符数组

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            System.out.println(calculate(str));
        }
    }

    private static int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char[] chs = s.toCharArray();
        int len = s.length(), number = 0;
        char sign = '+';
        for (int i = 0; i < len; i++) {
            char c = chs[i];
            if (c == ' ') continue;
            if (Character.isDigit(c)) {
                // c - '0'计算差值
                number = number * 10 + c - '0';
            }
            // 计算()内的值
            if (c == '(') {
                int j = i + 1, count = 1;
                while (count > 0) {
                    if (chs[j] == ')') count--;
                    if (chs[j] == '(') count++;
                    j++;
                }
                number = calculate(s.substring(i + 1, j - 1));
                i = j - 1;
            }
            // 利用栈先进后出
            if (!Character.isDigit(c) || i == len - 1) {
                if (sign == '+') {
                    stack.push(number);
                } else if (sign == '-') {
                    stack.push(-1 * number);
                } else if (sign == '*') {
                    stack.push(stack.pop() * number);
                } else if (sign == '/') {
                    stack.push(stack.pop() / number);
                }
                sign = c;
                number = 0;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }
}

全部评论

相关推荐

狸猫换offer:埋点都出来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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