My easy-understanded python solution in 160 ms


  • 1
    E

    For example,If the roman is "DCXXI",D has no last_number,so we plus the D=500.C is small than its last_number "D",so we plus C=100.go on and on,we get 621.
    When the roman is "CDXXI",the D is bigger than its last_number C,we need to minus the C.But we have plus the C before,so we should minus the C twice.
    If you are Chinese,there is a Chinese website show the difference between roman and integer.
    http://www.cnblogs.com/dosxp/archive/2008/08/13/1266781.html

       roman_dict={"M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1}
        last_num = 0
        result_num = 0
        for i in s:
            if roman_dict[i] <= last_num:
                result_num = result_num + roman_dict[i]
            else:
                result_num = result_num -2*last_num + roman_dict[i]
            last_num = roman_dict[i]
        return result_num

Log in to reply
 

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