class Solution {
public:
int getNumber(string& expression, int& pos){
int result = 0;
while(isdigit(expression[pos]) && pos < expression.size()){
result = result * 10 + (expression[pos] - '0');
pos++;
}
return result;
}
int parseFactor(string& expression, int& pos){
if(expression[pos] == '('){
pos++;
int result = parseExpression(expression, pos);
pos++;
return result;
}
return getNumber(expression, pos);
}
int parseTerm(string& expression, int& pos){
int result = parseFactor(expression, pos);
while(pos < expression.size() && (expression[pos] == '*' || expression[pos] == '/')){
char op = expression[pos++];
int nextFactor = parseFactor(expression, pos);
if(op == '*'){
result *= nextFactor;
} else if(op == '/'){
result /= nextFactor;
}
}
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);
}
};