[백준] 1935 후위표기식 2

cheeeese·2022년 4월 22일
0

코딩테스트 연습

목록 보기
86/151
post-thumbnail

📖 문제

https://www.acmicpc.net/problem/1935

💻 내 코드

n=int(input())
res=list(input())
nums=[]

for i in range(n):
    nums.append(int(input()))

stack=[]

for i in range(len(res)):
    if 'A'<=res[i]<='Z':
        stack.append(nums[ord(res[i])-ord('A')])
    else:
        x2=stack.pop()
        x1=stack.pop()

        if res[i]=='+':
            stack.append(x1+x2)
        elif res[i]=='-':
            stack.append(x1-x2)
        elif res[i]=='*':
            stack.append(x1*x2)
        elif res[i]=='/':
            stack.append(x1/x2)

print("%.2f" %stack[0])

💡 풀이

  • nums[ord(res[i])-ord('A')]: 숫자가 저장된 리스트에서 인덱스 값 계산
  •  `x2=stack.pop(); x1=stack.pop(`: 먼저 나온 숫자를 연산자 뒤에 사용되는 숫자로 잡음
  • "%.2f" %stack[0]: 소숫점 둘째자리까지 출력

0개의 댓글