罗马数字由7个符号表示:I
, V
, X
, L
, C
, D
和 M
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如罗马数字II
指两个1相加。12表示为
XII
,就是
X+II
。27为
XXVII
,是
XX+V+II
。
罗马数字排列格式为从左到右、从大到小。但是,4不是表示为
IIII
。相反,它表示为
IV
。因为如果存在小的罗马数字在大的之前,我们就需要用大的减去小的,这里就是5-1。9也是一样的规律,表示为
IX
。
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
1:正常思路暴力破解。先将罗马数字单独一个一个转换成数字列表。然后遍历,选判断是否为最后一个数字,如果是最后一个数字就直接加上该值。如果不是最后一个,再判断左右大小,如果左小就减去该值,其余均加。
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
temp_list = []
for i in s:
if i == 'I':
temp_list.append(1)
elif i == 'V':
temp_list.append(5)
elif i == 'X':
temp_list.append(10)
elif i == 'L':
temp_list.append(50)
elif i == 'C':
temp_list.append(100)
elif i == 'D':
temp_list.append(500)
elif i == 'M':
temp_list.append(1000)
for j in range(len(temp_list)):
if j == len(temp_list)-1:
result += temp_list[j]
else:
if temp_list[j]<temp_list[j+1]:
result -= temp_list[j]
else:
result += temp_list[j]
return result
2:字典简约的方法
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
temp_dict = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
for i in range(len(s)-1):
if temp_dict[s[i]]<temp_dict[s[i+1]]:
result -= temp_dict[s[i]]
else:
result += temp_dict[s[i]]
result += temp_dict[s[-1]]
return result
算法题来自:https://leetcode-cn.com/problems/roman-to-integer/description/