224. 基本计算器

2021/12/20 23:49:51

本文主要是介绍224. 基本计算器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

class Solution {

    private void pushStack(Stack<Integer> stack, char sign, int num) {
        if (sign == '+') {
            stack.push(num);
        } else if (sign == '-') {
            stack.push(-num);
        } else if (sign == '*') {
            stack.push(stack.pop() * num);
        } else if (sign == '/') {
            stack.push(stack.pop() / num);
        }
    }

    private int[] solve(String str, int index) {
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        char sign = '+';
        while (index < str.length() && str.charAt(index) != ')') {
            if (Character.isDigit(str.charAt(index))) {
                num = num * 10 + str.charAt(index++) - '0';
            } else if (str.charAt(index) == '(') {
                int[] next = solve(str, index + 1);
                index = next[0] + 1;
                num = next[1];
            } else if (str.charAt(index) == ' ') {
                index++;
            } else {
                pushStack(stack, sign, num);
                num = 0;
                sign = str.charAt(index++);
            }
        }
        pushStack(stack, sign, num);
        int sum = stack.stream().reduce(0, Integer::sum).intValue();
        return new int[]{index, sum};
    }

    public int calculate(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        return solve(s, 0)[1];
    }

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


这篇关于224. 基本计算器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程