python罗马数字转整数
时间: 2023-01-29 19:27:26 浏览: 52
Python罗马数字转整数的代码如下:
```
def roman_to_int(roman_string: str) -> int:
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for i in range(len(roman_string)):
if i > 0 and roman_dict[roman_string[i]] > roman_dict[roman_string[i - 1]]:
result += roman_dict[roman_string[i]] - 2 * roman_dict[roman_string[i - 1]]
else:
result += roman_dict[roman_string[i]]
return result
```
罗马数字转整数的基本思路是:
1. 建立罗马数字和对应整数的映射关系,如 {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
2. 初始化结果为 0
3. 从前往后遍历罗马数字字符串,对于每个字符:
1. 如果当前字符代表的数字比前一个字符代表的数字大,则加上当前字符代表的数字减去 2 倍的前一个字符代表的数字,例如 IV=4, IX=9
2. 否则直接加上当前字符代表的数字
4. 返回结果
示例:
```
>>> roman_to_int("IV")
4
>>> roman_to_int("IX")
9
>>> roman_to_int("XL")
40
>>> roman_to_int("MCMIV")
1904
```