SeangG
def _(): _()
SeangG
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Programming Language (0)
      • Python (0)
      • Web (0)
    • Algorithm (34)
    • Art (0)
      • 3D Modeling (0)
      • Pixel (0)
      • Picture (0)
    • Game (0)
    • Project (3)
      • Problems (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 매핑 테이블
  • BFS
  • dfs
  • 문자열
  • Daily Question
  • github oauth
  • leetcode
  • Fast Refresh
  • react.js
  • graph
  • WSL
  • Leecode
  • Tree
  • 로마 숫자
  • spring boot
  • string
  • Queue
  • next.js
  • LeedCode
  • Python

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
SeangG

def _(): _()

Algorithm

[LeetCode] 12. Integer to Roman

2024. 4. 2. 11:39

문제


Given an integer, convert it to a roman numeral.

1 <= num <= 3999

 

숫자가 주어지면 로마 숫자로 변환하는 문제이다.

예를 들면, 1994가 주어졌을 때 MCMXCIV를 반환하면 된다.


 

풀이


아이디어

각 자릿수에 대한 경우의 수가 많지 않다. (4 * 10 * 10 * 10; 0을 포함)

따라서 미리 정의한 후에 변환한다.

 

코드

class Solution:
    def intToRoman(self, num: int) -> str:
        # 경우의 수가 많지 않기 때문에 각 자릿수에 대한 로마자 표기를 미리 정의
        thousands = ['M'*i for i in range(4)]
        hundreds = ['C'*i for i in range(4)] + ["CD"] + ["D"+"C"*i for i in range(4)] + ["CM"]
        tens = ['X'*i for i in range(4)] + ["XL"] + ["L"+"X"*i for i in range(4)] + ["XC"]
        ones = ['I'*i for i in range(4)] + ["IV"] + ["V"+"I"*i for i in range(4)] + ["IX"]

        # 앞에 0을 채워서 코드 단순화
        # ex) 1 -> 0001, 23 -> 0023
        num_s = str(num).zfill(4)
        return thousands[int(num_s[0])] + hundreds[int(num_s[1])] + tens[int(num_s[2])] + ones[int(num_s[3])]

 

후기


난이도

경우의 수가 많지 않다는 것을 파악하면 쉽게 구현할 수 있다.

 

로마 숫자의 범위가 거의 안 쓰는 F(5000)를 포함하더라도 원래 작지만,

만약 더 큰 수를 나타내는 표기가 많아져 주어지는 수의 범위가 커지더라도,

규칙성을 이용해 쉽게 풀 수 있을 것이다.

 

다른 풀이

경우의 수를 미리 정의하지 않고 if문을 통해 처리하면 시간과 메모리를 아낄 수 있지 않을까 싶다.

단, 숫자가 여러 번 주어진다면 경우의 수를 미리 정의하는 것이 빠르다.

'Algorithm' 카테고리의 다른 글

[LeetCode] 1544. Make The String Great (Daily Question)  (0) 2024.04.05
[LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings  (0) 2024.04.04
[LeetCode] 1614. Maximum Nesting Depth of the Parentheses (Daily Question)  (0) 2024.04.04
[LeetCode] 79. Word Search (Daily Question)  (0) 2024.04.03
[LeetCode] 205. Isomorphic Strings (Daily Question)  (1) 2024.04.02
    'Algorithm' 카테고리의 다른 글
    • [LeetCode] 1111. Maximum Nesting Depth of Two Valid Parentheses Strings
    • [LeetCode] 1614. Maximum Nesting Depth of the Parentheses (Daily Question)
    • [LeetCode] 79. Word Search (Daily Question)
    • [LeetCode] 205. Isomorphic Strings (Daily Question)
    SeangG
    SeangG

    티스토리툴바