美文网首页Leetcode每日两题程序员
Leetcode 227. Basic Calculator I

Leetcode 227. Basic Calculator I

作者: ShutLove | 来源:发表于2017-12-14 18:13 被阅读51次

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;
}

相关文章

网友评论

    本文标题:Leetcode 227. Basic Calculator I

    本文链接:https://www.haomeiwen.com/subject/frbkwxtx.html