Pagini recente » Cod sursa (job #62389) | Cod sursa (job #1459930) | Cod sursa (job #1286352) | Cod sursa (job #1712380) | Cod sursa (job #2816934)
#include <bits/stdc++.h>
using namespace std;
ifstream fin( "evaluare.in" );
ofstream fout( "evaluare.out" );
string s;
stack <int> val;
stack <int> op;
bool isOperator( char c ) {
if( strchr( "+-/*", c ) ) return true;
return false;
}
int operatorPriority( char c ) {
if( c == '(' || c == ')' ) return 0;
if( c == '+' || c == '-' ) return 1;
if( c == '*' || c == '/' ) return 2;
}
int operate( int a, int b, char op ) {
if( op == '+' ) return a + b;
if( op == '-' ) return a - b;
if( op == '*' ) return a * b;
if( op == '/' ) return a / b;
}
int main()
{
fin >> s;
int nr = 0;
for( int i = 0; i < s.size(); ++i ) {
if( isdigit( s[i] ) ) {
nr = 0;
while( i < s.size() && isdigit( s[i] ) ) {
nr = nr * 10 + s[i] - '0';
i++;
}
i--;
val.push( nr );
continue;
}
if( s[i] == '(' ) {
op.push( '(' );
continue;
}
if( s[i] == ')' ) {
while( op.size() > 0 && op.top() != '(' ) {
int a, b;
char opr;
int answer;
b = val.top();
val.pop();
a = val.top();
val.pop();
opr = op.top();
op.pop();
answer = operate( a, b, opr );
val.push( answer );
}
op.pop();
continue;
}
if( isOperator( s[i] ) ) {
while( op.size() > 0 && operatorPriority( op.top() ) > operatorPriority( s[i] )) {
int a, b;
char opr;
int answer;
b = val.top();
val.pop();
a = val.top();
val.pop();
opr = op.top();
op.pop();
answer = operate( a, b, opr );
val.push( answer );
}
op.push( s[i] );
}
}
while( op.size() > 0 ) {
int a, b;
char opr;
int answer;
b = val.top();
val.pop();
a = val.top();
val.pop();
opr = op.top();
op.pop();
answer = operate( a, b, opr );
val.push( answer );
}
fout << val.top();
return 0;
}