使用单一的函数来转换罗马数字到整数,并确保它是正确的。下面是示例代码,它将从字符串中读取罗马数字,用循环遍历并计算结果:
def roman_to_int(s: str) -> int:
roman_to_int_map = {'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_to_int_map[s[i]] > roman_to_int_map[s[i-1]]:
result += roman_to_int_map[s[i]] - 2 * roman_to_int_map[s[i-1]]
else:
result += roman_to_int_map[s[i]]
return result
使用该函数,将罗马数字转换为整数将生成相同的结果。例如,roman_to_int('III')
将返回3,而不是每个函数生成的不同结果。