LeetCode #13 – Roman to Integer

LeetCode题目链接

Given a roman numeral, convert it to an integer.

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

题意:给定一个罗马数字字符串,将他转化为阿拉伯整数。

class Solution:
    def romanToInt(self, s):
        dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        num, pos = 0, 0
        while pos < len(s):
            if pos < len(s)-1 and dict[s[pos]] < dict[s[pos+1]]:
                num += dict[s[pos+1]] - dict[s[pos]]
                pos += 2
            else:
                num += dict[s[pos]]
                pos += 1
        return num

欢迎留言