최대 1 분 소요

사용 언어: Python3

문제

스크린샷 2023-04-26 오후 3 26 36

풀이

내 풀이

def calc(a,b,symb):
    a, b = int(a), int(b) # str을 int로 변경
    if symb == '+':
        return a + b
    if symb == '-':
        return a - b
    if symb == '*':
        return a * b
    if symb == '/':
        return a // b

lst = list(input())

stack = []
for x in lst:
    if x not in '+-*/()':
        stack.append(x)
    else:
        a, b = stack.pop(), stack.pop()
        stack.append(calc(b,a,x))

print(''.join(map(str, stack)))
  • 입력으로 주어지는 후위식에는 괄호가 없나..?
    • 맞음!

다른 풀이

lst = input()

stack = []
for x in lst:
    if x.isdecimal():
        stack.append(int(x)) # ✅ 여기서 int로 집어넣기
    else:
        a, b = stack.pop(), stack.pop()
        if x == '+':
            stack.append(b+a)
        elif x == '-':
            stack.append(b-a)
        elif x == '*':
            stack.append(b*a)
        else:
            stack.append(b//a)

print(stack[0]) # ✅ 스택에는 한 개만 남을 것


💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기