Skip to content

227. Basic Calculator II

Jacky Zhang edited this page Oct 12, 2016 · 3 revisions

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

Note: Do not use the eval built-in library function.

解题思路为采用stack,将带符号的数字存储起来,如遇'*'和'/',将计算后的结果存在stack中。 最后将stack中元素相加即可,这个过程也可在将元素存在stack时同时进行。

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0) return 0;
        int len = s.length();
        Stack<Integer> stack = new Stack<>();
        char sign = '+';
        int res = 0, num = 0;
        for(int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if(Character.isDigit(c)) {
                num = num * 10 + c - '0';
            }
            // cannot write else if, in case of "1" 
            if((!Character.isDigit(c) && c != ' ') || i == len-1) {
                if(sign == '+' || sign == '-') {
                    num = sign == '+' ? num : -num;
                    res += num;
                } else {
                    int old = stack.pop();
                    num = sign == '*' ? old * num : old / num;
                    res = res - old + num;
                }
                stack.push(num);
                sign = c;
                num = 0;
            }
        }
        return res;
    }
}
Clone this wiki locally