Basic Calculator

Basic Calculator


Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

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


public class Solution {
    public int calculate(String s) {
        if (s == null || s.length() == 0)
            return Integer.MAX_VALUE;
        
        Stack<Integer> stack = new Stack<Integer>();
        int number = 0;
        int sign = 1;
        int result = 0;
        
        for (int i = 0; i < s.length(); i++) {
            
            char c = s.charAt(i);
            
            if (Character.isDigit(c)) {
                number = number * 10 + (int)(c - '0');
            } else if (c == '+') {
                result = result + number * sign;
                sign = 1;
                number = 0;
            } else if ( c == '-') {
                result = result + number * sign;
                sign = -1;
                number = 0;
            } else if (c == '(' ){
                stack.push(result);
                stack.push(sign);
                result = 0;
                sign = 1;
            } else if (c == ')') {
                result = result + sign * number;
                number = 0;
                result = result * stack.pop();
                result = result + stack.pop();
            }
            
           
            
        }
        if(number != 0)
                result = result + number * sign;
            
        return result;
    }
}


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章