今天是紀錄LeetCode解題的第十三天
第十三題題目:Given a roman numeral, convert it to an integer.
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
給定羅馬符號,將其轉成整數
例如:2寫成羅馬數字II,就是兩個一相加,12寫成XII,就是X + II,數字27寫成XXVII,就是XX + V + II
羅馬數字通常從左到右按從大到小的順序書寫,然而,表示四的數字不是IIII。相反,數字四寫作IV。因為一在五之前,所以我們減去一,得到四。同樣的原則也適用於數字九,它寫作IX。
減法的使用有六種情況:
class Solution:
def romanToInt(self, s: str) -> int:
roman_map = {
'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000
}
prev = 0
total = 0
for c in s:
cur = roman_map[c]
if cur > prev:
total += cur - 2 * prev
else:
total += cur
prev = cur
return total
這題邏輯也和上一題一樣簡單,我們建立一個字典,抓取讀到的羅馬符號,如果該羅馬符號數值大於前一個羅馬符號,代表是用減法,那麼我們總數值就要減掉前一次加過的值和本次須減掉的值,總共需減去兩次,如果沒有大於前一個羅馬符號的數值,就正常做加法即可
初始狀態
第一次執行(c = C)
第二次執行(c = M)
第三次執行(c = X)
第四次執行(c = X)
最後回傳920就是答案