Clean and simple Python Solution


  • 0
    K

    Keep adding the value of the character. For every case where the previous value was less than the current value, subtract twice of the previous value to compensate for "wrong" addition.

        def romanToInt(self, s):
            d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 }
            prev, res = 0, 0
            for c in s:
                res += d[c]
                if prev < d[c]:
                    res -= 2*prev
                prev = d[c]
            return res
    

Log in to reply
 

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