Python Solution (easy to understand)

  • 0
        def romanToInt(self, s):
            :type s: str
            :rtype: int
            # Roman alphabetical order
            # Roman letters to decimal number dict
            omap={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
            # total decimal number
            # the last letter's index in 'Roman alphabetical order'
            # 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]
                    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.