#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int pred(char op){
if(op == '+'||op == '-')
return 1;
if(op == '*'||op == '/')
return 2;
return 0;
}
int perform_opr(int a, int b, char op){
switch(op){
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
int evaluate(string t){
int i;
stack <int> vals;
stack <char> ops;
for(i = 0; i < t.length(); i++){
if(t[i] == ' ')
continue;
else if(t[i] == '('){
ops.push(t[i]);
}
else if(isdigit(t[i])){
int val = 0;
while(i < t.length() &&
isdigit(t[i]))
{
val = (val*10) + (t[i]-'0');
i++;
}
vals.push(val);
i--;
}
else if(t[i] == ')')
{
while(!ops.empty() && ops.top() != '(')
{
int v2 = vals.top();
vals.pop();
int v1 = vals.top();
vals.pop();
char op = ops.top();
ops.pop();
vals.push(perform_opr(v1, v2, op));
}
if(!ops.empty())
ops.pop();
}
else
{
while(!ops.empty() && pred(ops.top())
>= pred(t[i])){
int v2 = vals.top();
vals.pop();
int v1 = vals.top();
vals.pop();
char op = ops.top();
ops.pop();
vals.push(perform_opr(v1, v2, op));
}
ops.push(t[i]);
}
}
while(!ops.empty()){
int v2 = vals.top();
vals.pop();
int v1 = vals.top();
vals.pop();
char op = ops.top();
ops.pop();
vals.push(perform_opr(v1, v2, op));
}
return vals.top();
}
int main() {
cout << evaluate("30 - 2 * 2 / 8 - 3") << "\n";
return 0;
}
Comments
Leave a comment