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

 

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

 

以 3 + 2 * 2为例,这道题的重点是在循环到发现当前字符是*时,才对2进行处理 (push 2),然后更新sign。

public class Solution {
    public int calculate(String s) {
        s = s.replace(" ", "");
        int num = 0;
        char sign = '+';
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < s.length(); ++i) {
            if(Character.isDigit(s.charAt(i))) {
                num = num * 10 + (s.charAt(i) - '0');
            }
            if(!Character.isDigit(s.charAt(i)) || i == s.length() - 1) {
                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);;
                } 
                sign = s.charAt(i);
                num = 0;
            }
        }

        int res = 0;
        for(int ele: stack) {
            res += ele;
        }
        return res;
    }
}

 

posted @ 2015-10-31 09:55  Phoebe815  阅读(117)  评论(0编辑  收藏  举报