Roman to Integer

Question

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Tags

  • String
  • Mathematics

Thought

Reference: http://www.cnblogs.com/zuoyuan/p/3779688.html

This is problem is not clear about the rule for conversion actually.

Code

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        numerals = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
        sum=0
        s=s[::-1]
        last=None
        for x in s:
            if last and numerals[x]<last:
                sum-=2*numerals[x]
            sum+=numerals[x]
            last=numerals[x]
        return sum

results matching ""

    No results matching ""