227. Basic Calculator II
class Solution {
public int calculate(String s) {
// stack to keep previous numbers
Stack<Integer> stack = new Stack<>();
char sign = '+';
int num = 0;
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
//if is number
if(isDigit(ch)){
num=10*num+(ch-'0');
}
if(!isDigit(ch) && ch!=' '|| i==s.length()-1){
switch(sign){
case '+':
stack.push(num);
break;
case '-':
stack.push(-1*num);
break;
case '*':
stack.push(num*stack.pop());
break;
case '/':
stack.push(stack.pop()/num);
break;
}
sign = ch;
num=0;
}
}
int sum = 0;
while(!stack.isEmpty()){
sum+=stack.pop();
}
return sum;
}
private boolean isDigit(char ch){
return ch>='0' && ch<= '9';
}
}
Last updated
Was this helpful?