Leetcode 227. Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, , / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
“3+2
2″ = 7
” 3/2 ” = 1
” 3+5 / 2 ” = 5

思路:
关键在于怎么处理乘法和除法,如果是乘法或者除法,我们需要用前面的数和当前的数做运算。因此此处可以用栈来记录前面的数字,用一个符号变量记录前一个符号,当遍历到一个新数字时,判断一下前面的符号是什么,如果是乘除,就和前面的数字运算,如果是+,就向栈中push这个数字,如果是-,就push这个数字的负数。
遍历到结尾,把最后一个数字入栈,此时栈中存放的都是要进行加法运算的数字。

public int calculate(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    int num = 0, res = 0;
    char op = '+';
    Stack<Integer> stack = new Stack<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (Character.isDigit(c)) {
            num = num * 10 + c - '0';
        }
        if (i == s.length() - 1 || (!Character.isDigit(c) && c != ' ')) {
            if (op == '+') {
                stack.push(num);
            } else if (op == '-') {
                stack.push(-num);
            } else if (op == '*') {
                stack.push(stack.pop() * num);
            } else if (op == '/') {
                stack.push(stack.pop() / num);
            }
            op = c;
            num = 0;
        }
    }
    while (!stack.isEmpty()) {
        res += stack.pop();
    }

    return res;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/a69e8722c493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞