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.
Answer:
public class Solution {
// "1 + 1 = 2"
public int calculate(String s) {
if(s==null || s.length() == 0) return 0;
int res = 0;
int sign = 1;
int len = s.length();
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<len;++i){
char c = s.charAt(i);
if(Character.isDigit(c)){
//calculate number here.
int number = 0;
number = c-'0';
while(i+1<len && Character.isDigit(s.charAt(i+1))){
number = number*10 + s.charAt(++i) - '0';
}
res = res + sign * number;
}
else if(c=='+'){
sign = 1;
}
else if(c=='-'){
sign = -1;
}
else if(c=='('){
stack.push(res);
stack.push(sign);
//recalculate in the '(xxx)' wrapper now.
res=0;
sign=1;
}
else if(c==')'){
if(stack.empty()==false){
sign = stack.pop();
}
if(stack.empty()==false){
res = stack.pop() + sign * res;
}
}
}
return res;
}
}
No comments:
Post a Comment