@@ -0,0 +1,1578 @@
+import java.util.Stack;%0A%0A/**%0A * Implement a basic calculator to evaluate a simple expression string.%0A *%0A * The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers%0A * and empty spaces.%0A *%0A * You may assume that the given expression is always valid.%0A *%0A * Some examples:%0A *%0A * %221 + 1%22 = 2%0A *%0A * %222 - 1 + 2%22 = 3%0A *%0A * %22(1+(4+5+2)-3)+(6+8)%22 = 23%0A *%0A * Note: Do not use the eval built-in library function.%0A *%0A * Tags: Stack, Math%0A *%0A * Similar Problems: (M) Evaluate Reverse Polish Notation, (M) Basic Calculator II, (M) Different Ways to Add%0A * Parentheses, (H) Expression Add Operators%0A */%0Apublic class BasicCalculator %7B%0A%0A    public int calculate(String s) %7B%0A        if (s == null %7C%7C s.length() == 0) %7B%0A            return 0;%0A        %7D%0A%0A        int result = 0;%0A        int sign = 1; // sign of the current context%0A        int num = 0;%0A%0A        Stack%3CInteger%3E stack = new Stack%3C%3E();%0A        stack.push(sign); // start with +1%0A        for (char c : s.toCharArray()) %7B%0A            if (c %3E= '0' && c %3C= '9') %7B // current number%0A                num = num * 10 + (c - '0');%0A            %7D else if (c == '+' %7C%7C c == '-') %7B // number finishes%0A                result += sign * num;%0A                sign = stack.peek() * (c == '+' ? 1 : -1);%0A                num = 0;%0A            %7D else if (c == '(') %7B // sign outside of parantheses%0A                stack.push(sign);%0A            %7D else if (c == ')') %7B%0A                stack.pop();%0A            %7D%0A        %7D%0A        result += sign * num; // last number%0A        return result;%0A    %7D%0A%7D%0A

add 224 Basic Calculator