Python code


  • 0
    G

    class Solution(object):
    def romanToInt(self, s):
    """
    :type s: str
    :rtype: int
    """
    roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

        num = 0
        while s:
            if ((len(s)==1) or (roman[s[0]]>=roman[s[1]])):
                num+=roman[s[0]]
                s = s[1:]
            else:
                num+=(roman[s[1]]-roman[s[0]])
                s = s[2:]
        return num

Log in to reply
 

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