복's

[ LeetCode - 12 ] Integer to Roman 본문

알고리즘/LeetCode

[ LeetCode - 12 ] Integer to Roman

나복이 2023. 10. 31. 04:27
728x90

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

 

Integer to Roman - LeetCode

Can you solve this real interview question? Integer to Roman - Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just tw

leetcode.com

처음에는 진짜 어떻게 풀라는건지 이해가 가지 않다가,  결국 모든 숫자를 미리 딕셔너리에 등록하는 방법으로 하기로 했다. (간단하고 편하니까) 그리고 다른 방법이 있는지 찾아 보니까 방법들은 있지만 근본적으로 풀이가 비슷하다고 느꼈다. 

 

이렇게 푸는게 잘못된건 아닌거 같다.


[ 📌 풀이 ]

딱히 풀이라고 할 것도 없는게 미리 로마 숫자를 등록 하고서는 큰 수부터 나눠 주면서 브루트 포스(Brute-Force) 방식으로 체크 해주면 된다.

 

백준에도 이런 비슷한 거스름돈 문제가 있었던걸로 기억한다.


[ 📌 코드 - Python ]

"""
# Author    : Lee In Bok 
# Date      : 2023.10.31(Tue)
# Spend Time: 14m 57s
# Runtime   : 47 ms (Beats 80.83%)
# Memory    : 16.1 MB (Beats 90.5%)
# Algoritm  : ?. ?
"""

class Solution:
    def intToRoman(self, num: int) -> str:
        dic = {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"}
        ans = ""

        for n in reversed(dic.keys()):
            result = num // n
            ans += dic[n] * result
            num %= n

        return ans

[ 📌 결과 ]

[ Result ]

728x90

'알고리즘 > LeetCode' 카테고리의 다른 글

[ LeetCode - 16 ] 3Sum Closest  (2) 2023.10.31
[ LeetCode - 52 ] N-Queens II  (1) 2023.10.31
[ LeetCode - 6 ] Zigzag Conversion  (1) 2023.10.31
[ LeetCode - 2 ] Add Two Numbers  (0) 2023.10.30
[ LeetCode - 22 ] Generate Parentheses  (1) 2023.10.30