LeetCode1.8

Roman to Integer

LeetCode1.8_第1张图片
Screen Shot 2019-01-08 at 10.35.13 PM.png
LeetCode1.8_第2张图片
Screen Shot 2019-01-08 at 10.35.19 PM.png

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

你可能感兴趣的:(LeetCode1.8)