Python beat 97% simple solution & explanation


  • 0
    R
     def romanToInt(self, s):
            d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
            ret = d[s[-1]] # b/c (len(s)-1) + 1 -> index out of range error; need to be (len(s)-2)+1
            for i in range(len(s)-2, -1, -1):
                if d[s[i]] < d[s[i+1]]: ret -= d[s[i]]
                else: ret += d[s[i]]
            return ret
    

Log in to reply
 

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