13.leetcode 罗马数字转整数(简单)

leetcode python 刷题记录,从易到难


一、题目

在这里插入图片描述
在这里插入图片描述


二、解答

1.思路

准备好对应的码表。分两种情况,第一种情况正常数字,III,MM之类的就直接加起来就好;第二种情况特殊数字,IV,IX之类的,相当于先减再加。

总结起来就是,前大后小的,相加即可。前小后大用累加值减去小值。

2.实现

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = 0
        transform_code_table = {
    
    "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
        for index in range(len(s) - 1):
            if transform_code_table[s[index + 1]] > \
                    transform_code_table[s[index]]:
                result = result - transform_code_table[s[index]]
            else:
                result = result + transform_code_table[s[index]]
        return result + transform_code_table[s[len(s) - 1]]

3.提交结果

在这里插入图片描述


三、Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/13.py


参考链接:

https://leetcode-cn.com/

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/107294955