解法一:使用字典映射
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
prev_value = 0
for c in s[::-1]:
current_value = roman_dict[c]
if current_value >= prev_value:
result += current_value
else:
result -= current_value
prev_value = current_value
return result
解法二:使用列表和条件判断
def roman_to_int(s):
roman_list = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
roman_value = [1, 5, 10, 50, 100, 500, 1000]
result = 0
prev_value = 0
for c in s[::-1]:
current_value = roman_value[roman_list.index(c)]
if current_value >= prev_value:
result += current_value
else:
result -= current_value
prev_value = current_value
return result
解法三:使用正则表达式替换
import re
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
pattern = re.compile('(IV|IX|XL|XC|CD|CM)')
s = pattern.sub(lambda x: str(roman_dict[x.group(0)[1]]) + str(roman_dict[x.group(0)[0]]), s)
result = sum([roman_dict[c] for c in s])
return result
解法四:使用循环和条件判断
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
i = len(s) - 1
while i >= 0:
if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
result += roman_dict[s[i]] - roman_dict[s[i-1]]
i -= 2
else:
result += roman_dict[s[i]]
i -= 1
return result
解法五:使用字典映射和循环
def roman_to_int(s):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for i in range(len(s)):
if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
result += roman_dict[s[i]] - 2 * roman_dict[s[i-1]]
else:
result += roman_dict[s[i]]
return result