声明:
因本人为AI路上的新手,文章用于辅助个人的整理记忆,理解难免有偏差之处,都是个人拙见,如给其他同僚造成困扰,还请见谅,非常非常非常欢迎私信共同讨论,共同进步
题目描述:
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, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: 3
Output: “III”
Example 2:
Input: 4
Output: “IV”
Example 3:
Input: 9
Output: “IX”
Example 4:
Input: 58
Output: “LVIII”
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: “MCMXCIV”
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4
解题思路:
- 既然罗马字符与阿拉伯数字有一一对应的关系,个位十位百位千位中,全部可以一一对应上,那就直接定义几个字典,包含每个位置上整数的映射,虽然麻烦,但有效
- 下面就开始从个位上遍历字符串,遇到是几,直接提取出值(也就是罗马字符),依次遍历,结束
- 见代码,一目了然
少废话,上代码:
class Solution:
def intToRoman(self, num) -> str:
#分别初始化个十百千,各个位上的罗马数字映射,方便后续查表
d0 = {"1": "I", "2": "II", "3": "III", "4": "IV", "5": "V",
"6": "VI", "7": "VII", "8": "VIII", "9": "IX"}
d1 = {"1": "X", "2": "XX", "3": "XXX", "4": "XL", "5": "L",
"6": "LX", "7": "LXX", "8": "LXXX", "9": "XC"}
d2 = {"1": "C", "2": "CC", "3": "CCC", "4": "CD", "5": "D",
"6": "DC", "7": "DCC", "8": "DCCC", "9": "CM"}
d3 = {"1": "M", "2": "MM", "3": "MMM"}
s_num = str(num)
ans = ""
for n, i in enumerate(reversed(s_num)):#从后向前遍历字符串,且记录第几个,代表是个位还是其他位
#遍历到那个位置上,就去查相应的位置字典表
if n == 0 and i in d0:
ans = d0.get(i) + ans
continue
if n == 1 and i in d1:
ans = d1.get(i) + ans
continue
if n == 2 and i in d2:
ans = d2.get(i) + ans
continue
if n == 3 and i in d3:
ans = d3.get(i) + ans
return ans
时间空间复杂度:
- Runtime: 52 ms, faster than 45.76% of Python3 online submissions for Integer to Roman.
- Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Integer to Roman.