本文共 1039 字,大约阅读时间需要 3 分钟。
为了将罗马数字转换为整数,我们可以使用一种简单而有效的方法:从左到右遍历每个字符。如果当前字符的值小于下一个字符的值,则减去当前字符的值;否则,加上当前字符的值。最后,将最后一个字符的值加到结果中。
class Solution: def romanToInt(self, s: str) -> int: roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} result = 0 for i in range(len(s) - 1): current = roman_values[s[i]] next_val = roman_values[s[i + 1]] if current < next_val: result -= current else: result += current result += roman_values[s[-1]] return result
roman_values
字典将罗马字符映射到对应的数值。result
变量初始化为0,用于存储最终的结果。for
循环遍历字符串的每个字符,直到倒数第二个字符。这种方法确保了我们能够正确地处理所有罗马数字,包括特殊情况,如4(IV)、9(IX)、40(XL)等。代码简洁且高效,能够在常数时间内完成转换任务。
转载地址:http://pcjxz.baihongyu.com/