
class Solution:
def romanToInt(self, s: str) -> int:
# 罗马数字与整数的映射
roman_to_int = {
'I': 1, 'V': 5, 'X': 10,
'L': 50, 'C': 100, 'D': 500, 'M': 1000
}
n = len(s)
total = 0
for i in range(n):
# 如果当前字符小于下一个字符,减去当前值
if i < n - 1 and roman_to_int[s[i]] < roman_to_int[s[i + 1]]:
total -= roman_to_int[s[i]]
else:
total += roman_to_int[s[i]]
return total

被折叠的 条评论
为什么被折叠?



