class Solution {
public:
int getNumber(string& expression, int& pos){
int result = 0;
while((isdigit(expression[pos]) || expression[pos] == ' ') && pos < expression.size()){
if(isdigit(expression[pos])){
result = result * 10 + (expression[pos] - '0');
}
pos++;
}
return result;
}
int parseTerm(string& expression, int& pos){
int result = getNumber(expression, pos);
while(pos < expression.size() && (expression[pos] == '*' || expression[pos] == '/')){
char op = expression[pos++];
int nextNumber = getNumber(expression, pos);
if(op == '*'){
result *= nextNumber;
} else if(op == '/'){
result /= nextNumber;
}
}
return result;
}
int parseExpression(string& expression, int& pos){
int result = parseTerm(expression, pos);
while(pos < expression.size() && (expression[pos] == '+' || expression[pos] == '-')){
char op = expression[pos++];
int nextTerm = parseTerm(expression, pos);
if(op == '+'){
result += nextTerm;
} else if(op == '-'){
result -= nextTerm;
}
}
return result;
}
int calculate(string s) {
int pos = 0;
return parseExpression(s, pos);
}
};