Cod sursa(job #3266990)
| Utilizator | Data | 10 ianuarie 2025 21:45:35 | |
|---|---|---|---|
| Problema | Evaluarea unei expresii | Scor | 40 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 2.29 kb |
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string s;
int main()
{
fin >> s;
stack<int> st;
stack<char> op;
int i = 0;
while (s[i])
{
if (s[i] >= '0' && s[i] <= '9')
{
int nr = 0;
while (s[i] >= '0' && s[i] <= '9')
{
nr = nr * 10 + s[i] - '0';
i++;
}
st.push(nr);
}
if (s[i] == ')')
{
while (op.top() != '(')
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
switch (op.top())
{
case '+':
st.push(a + b);
break;
case '-':
st.push(b - a);
break;
case '*':
st.push(a * b);
break;
case '/':
st.push(b / a);
break;
default:
break;
}
op.pop();
}
op.pop();
}
else if (s[i])
{
if (s[i] == '+' || s[i] == '-')
while (!op.empty() && (op.top() == '*' || op.top() == '/'))
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
if (op.top() == '*')
st.push(a * b);
else
st.push(b / a);
op.pop();
}
op.push(s[i]);
}
i++;
}
while (!op.empty())
{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
switch (op.top())
{
case '+':
st.push(a + b);
break;
case '-':
st.push(b - a);
break;
case '*':
st.push(a * b);
break;
case '/':
st.push(b / a);
break;
default:
break;
}
op.pop();
}
fout << st.top() << '\n';
return 0;
}
