简繁EN

LeetCodeNo. 092

[LeetCode with Python] 12. Integer to Roman

Contents

Problem

Problem page: https://leetcode.com/problems/integer-to-roman/
Topics: Math, String
Difficulty: Medium
Similar problems: (E) Roman to Integer, (M) Integer to English Words

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.


Analysis

Convert an int to its Roman numeral representation.
Roman numerals are pretty complicated, especially when you're converting between them and Arabic numerals. You might want to take a look at Wikipedia. It made my head spin, anyway, and I only got it after I found someone else's solution to this problem.
First, Roman numerals can't represent negative numbers or zero, so if you get an Arabic numeral like that, just return an empty string. The basic idea is to check the Roman numerals from largest to smallest. Each time, subtract the first value you can from the Arabic number num, and keep going until num is 0. Then comes the biggest problem: Roman numerals have combinations like IV (4) and XC (90), and there seem to be some conventions, too. You write 8 as VIII, not IIX, and only X can go to the left of C, not I, and so on. It couldn't get much more complicated. My advice: Rome fell for a reason, so let's not get too hung up on their culture. Put the individual Roman numerals and the conventional combinations in order from largest to smallest by value, then solve the problem using the basic idea above.
Space complexity is O(n). Time complexity is about O(n)?


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
# @return a string
def intToRoman(self, num):
if num <= 0:
return ""
nums = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
chs = ("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
len = 13
s = ""
while num > 0:
for i in range(0, len):
if num >= nums[i]:
num -= nums[i]
s += chs[i]
break
return s

Article link: https://xnerv.wang/en/leetcode-integer-to-roman/