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
// put all the number into stack 
// if + num -> stack
// if - -num -> stack
// if *,/ pop()/num
public class Solution {
    public int calculate(String s) {
        if(s == null || s.length()== 0) return 0;
        int res = 0;
        int curNum = 0;
        char sign = '+';
        Stack<Integer> stack = new Stack<>();
        for(int i = 0 ; i < s.length(); i++){
            char temp = s.charAt(i);
            if(temp == ' ') continue;
            else if(Character.isDigit(temp)){
                curNum = curNum * 10 + temp - '0';
            }
            else if(temp == '+'){
                stack.push(operation(sign, curNum, stack));
                curNum = 0;
                sign = '+';
            }
            else if(temp == '-'){
                stack.push(operation(sign, curNum, stack));
                curNum = 0;
                sign = '-';
            }
            else if(temp == '*'){
                stack.push(operation(sign, curNum, stack));
                curNum = 0;
                sign = '*';
            }
             else if(temp == '/'){
                stack.push(operation(sign, curNum, stack));
                curNum = 0;
                sign = '/';
            }
        }
        res = operation(sign, curNum, stack);
        while(!stack.isEmpty()){
            res += stack.pop();
        }
        return res;
        
    }
    
    public int operation(char sign, int number, Stack<Integer> stack){
        if(sign == '+')
            return number;
        else if(sign == '-')
            return -number;
        else if(sign == '*'){
            if(!stack.isEmpty())
                return stack.pop() * number;
        }
        else if(sign == '/'){
            if(!stack.isEmpty())
                return stack.pop() / number;
        }
        return number;    
    }
}
原文地址:https://www.cnblogs.com/joannacode/p/6120691.html