You are on page 1of 1

class Solution {

void eval(stack<char> &op, stack<int> &num) {


int b = num.top();
num.pop();
int a = num.top();
num.pop();

if (op.top() == '*')
num.push(a * b);
else if (op.top() == '/')
num.push(a / b);
else if (op.top() == '+')
num.push(a + b);
else if (op.top() == '-')
num.push(a - b);

op.pop();
}

public:
int calculate(string s) {
stack<char> op;
stack<int> num;
string operators("+-*/");
string digits("0123456789");
string number = "";

for (int i = 0; i < s.size(); ++i) {


if (operators.find(s[i]) != string::npos) {
num.push(atoi(number.c_str()));
number = "";

if (s[i] == '+' || s[i] == '-') {


while (!op.empty())
eval(op, num);
} else if (s[i] == '/' || s[i] == '*') {
while (!op.empty() && (op.top() == '/' || op.top() == '*'))
eval(op, num);
}

op.push(s[i]);
} else if (digits.find(s[i]) != string::npos) {
number += s[i];
}
}

num.push(atoi(number.c_str()));

while (!op.empty())
eval(op, num);

return num.top();
}
};

You might also like