LeetCode/Top Interview 150

12. Integer to Roman

hyunkookim 2024. 11. 28. 15:08

12. Integer to Roman

 

https://youtu.be/ohBNdSJyLh8?si=WM_rDigggPqJ_-PE

 

class Solution:
    def intToRoman(self, num: int) -> str:
        # 로마 숫자와 해당 값을 저장한 리스트
        # 로마 숫자는 큰 값에서 작은 값 순으로 정렬되어 있음
        symList = [["I", 1], ["IV", 4], ["V", 5], ["IX", 9],
                   ["X", 10], ["XL", 40], ["L", 50], ["XC", 90],
                   ["C", 100], ["CD", 400], ["D", 500], ["CM", 900],
                   ["M", 1000]]

        res = ""  # 결과 문자열을 저장할 변수

        # 로마 숫자를 큰 값에서 작은 값 순으로 순회 (리스트를 뒤집어서 사용)
        for sym, val in reversed(symList):
            # 현재 숫자(num)가 해당 값(val)로 나누어 떨어지는 경우만 처리
            if num // val:
                count = num // val  # 해당 로마 숫자가 몇 번 반복되는지 계산
                res += (sym * count)  # 로마 숫자를 count만큼 문자열에 추가
                num = num % val  # num을 val로 나눈 나머지를 갱신

        # 최종적으로 생성된 로마 숫자 문자열 반환
        return res

'LeetCode > Top Interview 150' 카테고리의 다른 글

28. Find the Index of the First Occurrence in a String  (0) 2024.11.28
6. Zigzag Conversion  (0) 2024.11.28
42. Trapping Rain Water  (0) 2024.11.28
14. Longest Common Prefix  (2) 2024.11.27
58. Length of Last Word  (0) 2024.11.27