Pagini recente » Cod sursa (job #1096267) | Cod sursa (job #2162017) | Cod sursa (job #530354) | Cod sursa (job #2788723) | Cod sursa (job #984412)
Cod sursa(job #984412)
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
void parse(char c, std::stack<long long>& myS)
{
long long a, b;
if(c == '+')
{
b = myS.top();
myS.pop();
a = myS.top();
myS.pop();
myS.push(a + b);
}
else if(c == '-')
{
b = myS.top();
myS.pop();
a = myS.top();
myS.pop();
myS.push(a - b);
}
else if(c == '*')
{
b = myS.top();
myS.pop();
a = myS.top();
myS.pop();
myS.push(a * b);
}
else if(c == '/')
{
b = myS.top();
myS.pop();
a = myS.top();
myS.pop();
myS.push(a / b);
}
}
long long reg(std::string& str)
{
std::stack<char> myS;
std::stack<long long> myI;
char c;
int a;
for(unsigned i = 0; i < str.length();)
{
if(str[i] == '(') myS.push('(');
else if(str[i] == ')')
{
while(myS.top() != '(')
{
c = myS.top();
parse(c, myI);
myS.pop();
}
myS.pop();
}
else if(str[i] == '+' || str[i] == '-')
{
while(!myS.empty() && myS.top() != '(')
{
c = myS.top();
parse(c, myI);
myS.pop();
}
myS.push(str[i]);
}
else if(str[i] == '*' || str[i] == '/')
{
while(!myS.empty() && myS.top() != '(' && myS.top() != '+' && myS.top() != '-')
{
c = myS.top();
parse(c, myI);
myS.pop();
}
myS.push(str[i]);
}
else
{
std::stringstream nstr;
while(str[i] >= '0' && str[i] <= '9')
{
nstr << str[i];
i++;
}
nstr >> a;
myI.push(a);
continue;
}
i++;
}
while(!myS.empty())
{
c = myS.top();
parse(c, myI);
myS.pop();
}
return myI.top();
}
int main()
{
std::ifstream in("evaluare.in");
std::ofstream out("evaluare.out");
std::string str;
getline(in, str);
out << reg(str);
return 0;
}