Posted on 2022-11-03 01:56
Uriel 閱讀(48)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code 、
大水題
羅馬數(shù)字轉(zhuǎn)阿拉伯數(shù)字,從左往右一位一位處理,如果當前遇到的羅馬字比前一位處理的要小,說明出現(xiàn)了4和9的情況,要減去兩倍的剛才疊加上的數(shù)
1 #13
2 #Runtime: 52 ms
3 #Memory Usage: 13.5 MB
4
5 class Solution(object):
6 def romanToInt(self, s):
7 """
8 :type s: str
9 :rtype: int
10 """
11 num = 0
12 pre_val = 1000
13 roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
14 for i in s:
15 num = num + roman_dict[i]
16 if pre_val < roman_dict[i]:
17 num = num - 2 * pre_val
18 pre_val = roman_dict[i]
19 return num