• 題目描述:給一個字串,依照題目給的表格,計算出字串對應的值並做加總

  • 思路:依照題目給的表格做一個字典,接著定義一個變數做加總,並依照題目所給的前一位的值小於當前的值時,做相對應的處理

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