Pagini recente » Cod sursa (job #328350) | Cod sursa (job #2687115) | Cod sursa (job #1166282) | Cod sursa (job #1859219) | Cod sursa (job #2789219)
#include <stdio.h>
#include <cstring>
#define NMAXX 100000
using namespace std;
char s[NMAXX], op[NMAXX], fact[NMAXX];
int n, i, opSize, factSize;
int priority( char ch ) {
if ( ch == '*' || ch == '/' )
return 2;
else if ( ch == '+' || ch == '-' )
return 1;
return 0;
}
void pushFact( int a ) {
fact[factSize++] = a;
}
void pushOp( char ch ) {
if ( ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')' )
op[opSize++] = ch;
}
int popFact() {
if ( factSize > 0 )
return fact[--factSize];
return 0;
}
char popOp() {
if ( opSize > 0 )
return op[--opSize];
return '\0';
}
char topOp() {
if ( opSize > 0 )
return op[opSize - 1];
return '\0';
}
int calcul( int a, int b, char ch ) {
int res = 0;
if ( ch == '*' )
res = a * b;
else if ( ch == '/' )
res = a / b;
else if ( ch == '+' )
res = a + b;
else if ( ch == '-' )
res = a - b;
return res;
}
void calculTop() {
int a, b;
b = popFact();
a = popFact();
pushFact( calcul( a, b, popOp() ) );
}
int element() {
int nr = 0;
while ( s[i] >= '0' && s[i] <= '9' ) {
nr *= 10;
nr += s[i] - '0';
i++;
}
return nr;
}
int main()
{
FILE *fin, *fout;
fin = fopen( "evaluare.in", "r" );
fout = fopen( "evaluare.out", "w" );
fgets( s, NMAXX, fin );
n = strlen( s );
i = 0;
while ( i < n ) {
if ( s[i] >= '0' && s[i] <= '9' )
pushFact( element() );
else if ( s[i] == '(' )
pushOp( s[i++] );
else if( s[i] == ')' ) {
while ( topOp() != '(' )
calculTop();
popOp();
i++;
} else if ( priority( s[i] ) != 0 ) {
while ( priority( topOp() ) && priority( topOp() ) >= priority( s[i] ) )
calculTop();
pushOp( s[i++] );
} else
i++;
}
while ( opSize > 0 )
calculTop();
fprintf( fout, "%d", popFact() );
fclose( fin );
fclose( fout );
return 0;
}