Pagini recente » Cod sursa (job #2257753) | Cod sursa (job #2835716) | Cod sursa (job #375305) | Cod sursa (job #1649949) | Cod sursa (job #1309638)
#include <cstdio>
#include <cctype>
#include <cstring>
#define SIZE 100004
using namespace std;
char s[SIZE], operator_st[SIZE];
int sol, len, operator_st_top, operand_st_top, operand_st[SIZE];
inline int priority( char c )
{
if( c == '*' || c == '/' || c == '%' )
return 2;
if( c == '+' || c == '-' )
return 1;
return 0;
}
inline int isoperator( char c )
{
if( strchr("+-*/%", c) )
return 1;
return 0;
}
inline int calc(int nr1, int nr2, char op)
{
//printf("%d %c %d ==", nr2, op, nr1);
if( op == '+' )
nr2 += nr1;
else if( op == '-' )
nr2 -= nr1;
else if( op == '*')
nr2 *= nr1;
else if( op == '/' )
nr2 /= nr1;
else if( op == '%')
nr2 %= nr1;
// printf(" %d\n", nr2);
sol = nr2;
return nr2;
}
int main()
{
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
s[0] = '(';
gets(s + 1);
len = strlen( s);
s[len] = ')';
int i = 0;
while( i <= len )
{
while ( isspace(s[i]) && i <= len )
++i;
if( s[i] == '(' )
operator_st[ ++operator_st_top ] = s[ i++ ];
if( isdigit(s[i]) )
{
int nr = 0;
while ( isdigit(s[i]) && i <= len )
{
nr = nr * 10 + s[i] - 48;
++i;
}
operand_st[ ++operand_st_top ] = nr;
}
if( isoperator( s[i] ) )
if ( operator_st_top == 0 || priority(operator_st[operator_st_top]) < priority(s[i]))
operator_st[ ++operator_st_top ] = s[ i++ ];
else
{
while (priority(operator_st[operator_st_top]) >= priority(s[i]) && operator_st_top > 0)
{
char op = operator_st[operator_st_top];
operator_st_top--;
int nr1 = 0, nr2 =0;
nr1 = operand_st[operand_st_top];
operand_st_top--;
nr2 = operand_st[operand_st_top];
operand_st[operand_st_top] = calc(nr1, nr2, op);
}
operator_st[ ++operator_st_top ] = s[ i++ ];
}
if( s[i] == ')' )
{
while( operator_st[operator_st_top] != '(')
{
// printf("%c!\n\n", s[i]);
char op = operator_st[operator_st_top];
int nr1 = 0, nr2 = 0;
nr1 = operand_st[operand_st_top];
operand_st_top--;
nr2 = operand_st[operand_st_top];
operand_st[operand_st_top] = calc(nr1, nr2, op);
--operator_st_top;
}
--operator_st_top;
++i;
}
}
// printf("%s", s);
printf("%d\n", sol);
return 0;
}