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.
只有加减的计算器, 用了如下几个变量
res表示当前计算的结果,
num表示当前的数字, 比如 123 + 1 中的123就需要多个字符组合起来
sign表示当前num之前的操作符是 + 还是 -,
‘(’ 代表需要把之前的res和左括号之前的sign 放到stack中,并且把状态清零,
‘)’ 表示需要把当前括号内的res计算出来, 出栈, res * sign就是加或者减括号内的结果 比如 1 - (1 + 2)
‘-’ 和 ‘+’ 表示当前字符已经不是digit了,所以num的计算已经结束, 可以结合之前的sign加到 res中, 然后 num要重新置零,
然后循环结束时还要把最后的 num 加上, 考虑这个例子 (12 - 23) + 5
// 21 - (20 - 3) + 5
public class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0)
return 0;
int num = 0;
int res = 0;
int sign = 1;
LinkedList<Integer> stack = new LinkedList<Integer>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
num = num * 10 + c - '0';
}else if(c == '+'){
res += num * sign;
sign = 1;
num = 0;
}else if(c == '-'){
res += num * sign;
sign = -1;
num = 0;
}else if(c == '('){
stack.push(res);
stack.push(sign);
res = 0;
num = 0;
sign = 1;
}else if(c == ')'){
res += num * sign;
num = 0;
sign = 1;
res *= stack.pop();
res += stack.pop();
}
}
res += num * sign;
return res;
}
}