I tried to solve the Problem224 on Leetcode. My code is below:
import java.util.Stack;
public class Calculator {
public int calculate(String s){
Stack <Integer> numst=new Stack<Integer>();
Stack <Character> oprst=new Stack<Character>();
Character c;
int i;
int number;
int length=s.length();
for(i=0;i<length;i++){
c=s.charAt(i);
switch(c){
case ' ':
continue;
case '(':
continue;
case '+':
oprst.push('+');
continue;
case '-':
oprst.push('-');
continue;
case ')':
if(numst.size()==2){
if(oprst.peek()=='+') {
numst.push(numst.pop() + numst.pop());
oprst.pop();
}
else if(oprst.pop()=='-') {
numst.push(-numst.pop() + numst.pop());
oprst.pop();
}
}
else
continue;
continue;
default:
if(i>0){
if(Character.isDigit(s.charAt(i-1))) {
numst.push(10 * numst.pop() + ('c' - '0'));
}
else
numst.push(('c'-'0'));
}
else
numst.push(('c'-'0'));
if(numst.size()==2){
if(oprst.peek()=='+') {
numst.push(numst.pop() + numst.pop());
oprst.pop();
}
else if(oprst.peek()=='-') {
numst.push(-numst.pop() + numst.pop());
oprst.pop();
}
}
else
continue;
continue;
}
}
return numst.pop();
}
}
I used two stacks. The numst stores the operands and results of every calculation. The opst stores the operator in the calculator expression.
When I put s="1 + 1" in the function, I got 102 as the answer. Can you tell me the problems in my code?