Leetcode #13 Roman to Integer

Description

Given a roman numeral, convert it to an integer.

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

Example

input: DCXXI
output: 621

Code

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        lm_dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
        ans = 0
        for i in range(0, len(s)):
            if i and lm_dict[s[i]] > lm_dict[s[i-1]]:
                ans -= lm_dict[s[i-1]] * 2
                ans += lm_dict[s[i]]
            else:
                ans += lm_dict[s[i]]
        return ans

你可能感兴趣的:(leetcode,leetcode)