Monday, July 6, 2015

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:
Add Your Encoded Code Here
   /* Method2:*/
    Stack stack = new Stack();
    stack.push(1);
    int res = 0;
    int sign = 1;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '+' || c == '-') {
            sign = c == '+' ? 1: -1;
        } else if (c == '(') {
            stack.push(sign * stack.peek());
            sign = 1;
        } else if (c == ')') {
            sign = stack.pop();
        } else if (Character.isDigit(c)) {
            int num = 0;
            while (i < s.length() && Character.isDigit(s.charAt(i))) {
                num = num * 10 + (s.charAt(i) - '0');
                i++;
            }
            i--;
            res += sign * num * stack.peek();
        }
    }
    return res;

No comments:

Post a Comment