Simple Python


  • 0

    The key idea is add the current char's corresponding value if it is smaller than previous one, or add the current value minus two more previous value when it is bigger.

    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            pre, ans = None, 0
            dic = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000, None: 10000}
            for c in s:
                ans += dic[c] if dic[pre] >= dic[c] else dic[c] - dic[pre] * 2
                pre = c
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.