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.
class Solution {
    public int calculate(String s) {
        Stack<Integer> stk = new Stack<Integer>();
        int res = 0, num = 0;
        char lastSign = '+';
        char[] cArray = s.toCharArray();
        
        for(int i=0; i < cArray.length; i++){
            char c = cArray[i];
            if(c >= '0' && c <= '9'){
                num = num*10 + c -'0';
            }
            
            if(c == '+' || c == '-' || c == '*' || c == '/' || i == cArray.length-1){
                if(lastSign == '+' || lastSign == '-'){
                    int temp = lastSign == '+' ? num : -num;
                    stk.push(temp);
                    res += temp;
                }
                if(lastSign == '*' || lastSign == '/'){
                    res -= stk.peek();
                    int temp = lastSign == '*' ? stk.pop()*num : stk.pop()/num;
                    stk.push(temp);
                    res += temp;
                }
                lastSign = c;
                num = 0;
            }
        }
        return res;
    }
}class Solution {
    public int calculate(String s) {
        // int[0] is value and int[1] is the operator
        int[] lstack = new int[2]; // low  priority stack for + -
        int[] hstack = new int[2]; // high priority stack for * /
        int val = 0;
        for (int i=0; i < s.length(); i++) {
          char ch = s.charAt(i);
          if (ch == ' ') continue;
          if (ch == '+' || ch == '-') {
            if (hstack[1] > 0) {
              val = hstack[1] == '*' ? (hstack[0] * val) : (hstack[0] / val);
              hstack[1] = 0;
            }
            if (lstack[1] > 0)
              val = lstack[1] == '+' ? (lstack[0] + val) : (lstack[0] - val);
            lstack[0] = val; lstack[1] = ch; val = 0;
          } else if (ch == '*' || ch == '/') {
            if (hstack[1] > 0)
              val = hstack[1] == '*' ? (hstack[0] * val) : (hstack[0] / val);
            hstack[0] = val; hstack[1] = ch; val = 0;
          } else
            val = val * 10 + ch - 48;
        }
        if (hstack[1] > 0)
          val = hstack[1] == '*' ? (hstack[0] * val) : (hstack[0] / val);
        if (lstack[1] > 0)
          val = lstack[1] == '+' ? (lstack[0] + val) : (lstack[0] - val);
        return val;
    }
}                










