TIL | 알고리즘 | 코드카타 6일 (2주 1일)

이도운·2022년 1월 16일
0

TIL

목록 보기
55/73
post-thumbnail

문제

로마자에서 숫자로 바꾸기 1~3999 사이의 로마자 s를 인자로 주면 그에 해당하는 숫자를 반환해주세요.

풀이

def roman_to_num(s):
  # 여기에 코드를 작성해주세요.
  roman = {
    "I" : 1,
    "V" : 5,
    "X" : 10,
    "L" : 50,
    "C" : 100,
    "D" : 500,
    "M" : 1000,
  }

  result = 0

  list_roman_str = list(s)

  for i in range(0, len(list_roman_str)):
    if i != (len(list_roman_str)-1):
      if list_roman_str[i] == "I" and (list_roman_str[i+1] == "V" or list_roman_str[i+1] == "X"):
        print("i :", i)
        result -= 1
      elif list_roman_str[i] == "X" and (list_roman_str[i+1] == "L" or list_roman_str[i+1] == "C"):
        print("i :", i)
        result -= 10
      elif list_roman_str[i] == "C" and (list_roman_str[i+1] == "D" or list_roman_str[i+1] == "M"):
        print("i :", i)
        result -= 100
      else:
        print("i :", i)
        result += roman[list_roman_str[i]]
    else:
        print("i :", i)
        result += roman[list_roman_str[i]]
  
  return result

print("결과 :", roman_to_num("III")) 
profile
⌨️ 백엔드개발자 (컴퓨터공학과 졸업)

0개의 댓글