Python solution


  • 12
    S
        def romanToInt(self, s):
    
            romans = {'M': 1000, 'D': 500 , 'C': 100, 'L': 50, 'X': 10,'V': 5,'I': 1}
    
            prev_value = running_total =0
            
            for i in range(len(s)-1, -1, -1):
                int_val = romans[s[i]]
                if int_val < prev_value:
                    running_total -= int_val
                else:
                    running_total += int_val
                prev_value = int_val
            
            return running_total

  • 0
    M

    kudos ! this is a really good solution - I have been thinking about this problem for more than a week . I was struggling with numbers like IV (4) , XL (40) , XC (90) etc., -- I was failing to capture this pattern in code. excellent work.

    So the idea here is to process from right to left ( instead of left to right ) ! cool .


  • 0
    S

    Yes sir. You're right on the idea. Glad it helped !


  • 0
    M

    :) Have you solved the reverse BTW ? Integer to Roman ? I m trying to solve that too !


  • 0
    S

    Yeah i did...I will add this here too.


Log in to reply
 

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