letcode 3. 羅馬數字轉整數

向右掃描,如果對應的字母代表的值小於右邊的,則執行機減法,比如:IV,先減一再加5,結果爲4。

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        R = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        result = 0
        for i in range(len(s)-1):
            if R[s[i]] < R[s[i + 1]]:
                result -= R[s[i]]
            else:
                result += R[s[i]]
        return result + R[s[-1]]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章