Pagini recente » Cod sursa (job #2346136) | Cod sursa (job #1944545) | Cod sursa (job #1264588) | Cod sursa (job #1228461) | Cod sursa (job #2871942)
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int order(char opr)
{
if(opr == '+' || opr == '-')
return 1;
if(opr == '*' || opr == '/')
return 2;
return 0;
}
int operation(int x, int y, char opr)
{
if(opr == '+')
return x+y;
if(opr == '-')
return x-y;
if(opr == '*')
return x*y;
if(opr == '/')
return x/y;
}
int solve(string str)
{
int i, len = str.length(),x, y, partial_res = 0, nr= 0 ;
char op;
stack <int> val;
stack <char> oprs;
for (i=0; i<len; i++)
{
if(isdigit(str[i]))
{
nr = 0;
while(i<len && isdigit(str[i]))
{
nr *= 10;
nr += (str[i] - '0');
i++;
}
i--;
val.push(nr);
}
else if(str[i] == ')') ///am intalnit o paranteza inchisa, deci trebuie sa rezolvam tot ce avem in paranteza din momentul in care s-a deschis
{
while(!oprs.empty() && oprs.top() != '(')
{
op = oprs.top();
oprs.pop();
y = val.top();
val.pop();
x = val.top();
val.pop();
partial_res = operation(x, y, op);
val.push(partial_res);
}
oprs.pop();
}
else
{
while(!oprs.empty() && order(oprs.top()) >= order(str[i]))
{
op = oprs.top();
oprs.pop();
y = val.top();
val.pop();
x = val.top();
val.pop();
partial_res = operation(x, y, op);
val.push(partial_res);
}
oprs.push(str[i]);
}
}
while(!oprs.empty())
{
op = oprs.top();
oprs.pop();
y = val.top();
val.pop();
x = val.top();
val.pop();
partial_res = operation(x, y, op);
val.push(partial_res);
}
return val.top();
}
int main()
{
cout << solve("(1+1)*13+10/2");
return 0;
}