1223. [S/W 문제해결 기본] 6일차 - 계산기2
문제 풀이
import sys
sys.stdin = open("input.txt", "r")
for tc in range(1, 11):
T = int(input())
TC = list(input())
priority = {'*': 2, '+': 1}
postfix = []
stack = []
for i in TC:
if i != '*' and i != '+':
postfix.append(i)
elif not stack:
stack.append(i)
else:
while stack and priority[stack[-1]] >= priority[i]:
postfix.append(stack.pop())
stack.append(i)
while stack:
postfix.append(stack.pop())
cal = []
for i in postfix:
if i != '+' and i != '*':
cal.append(int(i))
elif i == '*':
n1 = cal.pop()
n2 = cal.pop()
cal.append(n1 * n2)
elif i == '+':
n1 = cal.pop()
n2 = cal.pop()
cal.append(n1 + n2)
print(f"#{tc} {cal[0]}")