#include <stdio.h>
char infix[1001];
char postfix[1001];
int stack[1001];
int top;
void push(int num) {
stack[++top] = num;
}
int pop() {
return stack[top--];
}
int main()
{
freopen("input.txt", "r", stdin);
int T;
int length;
int idx;
int res;
int tmp1, tmp2;
int i;
for (T = 1; T <= 10; ++T)
{
top = -1;
idx = 0;
res = 0;
scanf("%d", &length);
scanf("%s", infix);
for (i = 0; i < length; ++i)
{
if ((infix[i] >= '0') && (infix[i] <= '9'))
postfix[idx++] = infix[i];
else if (infix[i] == '+') // 우선순위 낮음
{
while ((top > -1) && ((stack[top] == '+') || stack[top] == '*'))
postfix[idx++] = pop();
push(infix[i]);
}
else if (infix[i] == '*') // 우선순위 높음
{
while ((top > -1) && (stack[top] == '*'))
postfix[idx++] = pop();
push(infix[i]);
}
}
while (top > -1)
postfix[idx++] = pop(); // stack에 남아 있는 것 모두 옮기기
// 계산 시작
for (i = 0; i < idx; ++i)
{
if ((postfix[i] >= '0') && (postfix[i] <= '9'))
push(postfix[i] - '0');
else if (postfix[i] == '+')
{
tmp2 = pop();
tmp1 = pop();
push(tmp1 + tmp2);
}
else if (postfix[i] == '*')
{
tmp2 = pop();
tmp1 = pop();
push(tmp1 * tmp2);
}
}
printf("#%d %d\n", T, pop());
}
return 0;
}
댓글