Basic Calculator

来源:互联网 发布:淘宝京东哪个好 编辑:程序博客网 时间:2024/06/06 03:33

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.

思路:用stack来保存之前算过的值和符号,这里符号很重要,因为比如说括号前面是减号,那么括号计算出来的结果需要乘以之前的符号。计算的过程在遇见数字的时候,就已经进行了,stack里面只是需要存之前的计算结果。

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0) return 0;        int sign = 1; int result = 0;        Stack<Integer> stack = new Stack<Integer>();        for(int i=0; i<s.length(); i++){            char c = s.charAt(i);            if(c == ' '){                continue;            } else if( isdigit(c)){                int sum = c-'0';                while(i+1<s.length() && isdigit(s.charAt(i+1))){                    sum = sum*10 + s.charAt(i+1)-'0';                    i++;                }                result += sum * sign;            } else if(c == '+'){                sign = 1;            } else if(c == '-'){                sign = -1;            } else if( c == '('){                stack.push(result);                stack.push(sign);                sign = 1;                result = 0;            } else { // ')'                result = result*stack.pop() + stack.pop();            }        }        return result;    }        public boolean isdigit(char c){        return '0'<= c && c<='9';    }}


0 0