[LeetCode] 12. Integer to Roman

원숭2·2022년 1월 17일
0

LeetCode

목록 보기
8/51

문제

풀이

  1. 로마숫자와 정수를 Dictionary에 짝을 지어 추가해줌
  2. 주어진 정수를 자릿수 분해하여 res 배열에 append
  3. Dictionary의 key값을 뽑아서(keys() 활용) 내림차순으로 정렬 후 std로 선언
  4. res배열을 돌며 각 배열 요소의 값이 0이 될 때 까지 std의 인덱스를 조정해가며 빼줌

코드

class Solution:
    def intToRoman(self, num: int) -> str:     
        roman = {1 : 'I', 4 : 'IV', 5 : 'V', 9 : 'IX', 10 : 'X', 40 : 'XL', 50 : 'L', 90 : 'XC', 100 : 'C', 400 : 'CD', 500 : 'D', 900 : 'CM', 1000 : 'M'}
        num = str(num)

        res = []
        old_idx = 0
        for i in range(len(num)-1, -1, -1) :
            res.append(int(num[old_idx]) * (10 ** i))
            old_idx += 1

        fin = []
        std = sorted(list(roman.keys()), reverse = True)
        idx = 0
        for i in range(len(res)) :
            while res[i] != 0 :
                if std[idx] > res[i] :
                    idx += 1
                else :
                    res[i] -= std[idx]
                    fin.append(roman[std[idx]])

        return ''.join(fin)

0개의 댓글