I. Description


II. Code
class Solution:
def intToRoman(self, num: int) -> str:
res = 'M' * (num // 1000)
num %= 1000
val = num // 100
if val == 9:
res += 'CM'
elif val == 4:
res += 'CD'
else:
res += 'D' * (val // 5) + 'C' * (val % 5)
num %= 100
val = num // 10
if val == 9:
res += 'XC'
elif val == 4:
res += 'XL'
else:
res += 'L' * (val // 5) + 'X' * (val % 5)
num %= 10
if num == 9:
res += 'IX'
elif num == 4:
res += 'IV'
else:
res += 'V' * (num // 5) + 'I' * (num % 5)
return res
4와 9라는 특수한 상황을 잘 고려해가며 코드를 작성하였다.
'Coding Test > Hash Table' 카테고리의 다른 글
[LeetCode] 36. Valid Sudoku (0) | 2025.01.25 |
---|---|
[LeetCode] 17. Letter Combinations of a Phone Number (0) | 2025.01.25 |
[LeetCode] 1930. Unique Length-3 Palindromic Subsequences (0) | 2025.01.25 |
[LeetCode] 1943. Describe the Painting (0) | 2025.01.23 |
[LeetCode] 1942. The Number of the Smallest Unoccupied Chair (0) | 2025.01.22 |