파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 10. 20. 23:45

https://leetcode.com/problems/integer-to-roman/

 

Integer to Roman - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

뒤에서부터 앞으로 순회하면서 풀면 될 것 같긴 한데..
솔루션을 보니 뒤에서 가 아니라 큰 수부터 빼면 된다.

class Solution:
    def intToRoman(self, num: int) -> str:
        num_map = {
            1: "I", 5: "V", 4: "IV",
            10: "X", 9: "IX",
            50: "L", 40: "XL",
            100: "C", 90: "XC",
            500: "D", 400: "CD",
            1000: "M", 900: "CM",
        }
        
        res = ''        
        for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
            while n <= num:
                res += num_map[n]
                num -= n
        
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.10.22
Today's Challenge  (0) 2022.10.21
Today's Challenge  (0) 2022.10.19
Today's Challenge  (0) 2022.10.18
Today's Challenge  (0) 2022.10.17
Comments