Share my python code


  • 0
    J
    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            d_r = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
            exceptions = {'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900}
    
            i = 0
            result = 0
            while i<len(s):
                c = s[i]
                if i+2 <= len(s):
                    two = s[i:i+2]
                else:
                    two = None 
                if two in exceptions:
                        result += exceptions[two]
                        i += 2
                elif c in d_r:
                    result += d_r[c]
                    i += 1
                else:
                    print ('It is not Roman numbers.', s)
                    return
    
            return result
    

Log in to reply
 

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