Python Solution (easy to understand)


  • 0
    L
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            # Roman alphabetical order
            order='IVXLCDM'
            # Roman letters to decimal number dict
            omap={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
            
            # total decimal number
            num=0
            # the last letter's index in 'Roman alphabetical order'
            prev=-1
            
            # 1. reverse the Roman numerals
            # 2. calculate from the last digit
            # 3. add the decimal digits represented by each Roman numerals
            # 4. if current Roman numeral is smaller than the previous, subtract it from the total decimal number
            for i in s[::-1]:
                if order.index(i) < prev:
                    num -= self.omap[i]
                else:
                    num += self.omap[i]
                prev = order.index(i)
            return num
    

Log in to reply
 

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