4 lines in Python


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

  • 0
    Y
    This post is deleted!

  • 0
    R

    Very concise!


  • 0
    Y

    Smart solution


  • 0
    S

    Did something similar, but you can just iterate in order (and put the char -> int mapping in a list comp):

    map = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    
    def romanToInt(self, s):
        num, pre = 0, 1000
        for i in [map[j] for j in s]:
            num, pre = num + i - 2*pre if i > pre else num + i, i
        return num

  • 0
    Y

    excellent solution and very concise code! Thanks for ur share


  • 0
    I

    @Suralin said in 4 lines in Python:

    Did something similar, but you can just iterate in order (and put the char -> int mapping in a list comp):

    map = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    
    def romanToInt(self, s):
        num, pre = 0, 1000
        for i in [map[j] for j in s]:
            num, pre = num + i - 2*pre if i > pre else num + i, i
        return num

Log in to reply
 

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