題目
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
即將輸入的羅馬數字轉換成十進制阿拉伯數字。
羅馬數字的規律是:
左邊數字如果小於右邊數字的話,用右邊數字減去左邊數字;如果左邊數字大於右邊數字則執行加法。
如IV是5-1=4,VI是5+1=5。
詳細羅馬數字資料可參考:羅馬數字
解法 1
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# 最後一位羅馬數字不參與計算
result = dict[s[-1]]
# 從最後一位往前逆向
for i in range(len(s) - 2, -1, -1):
if dict[s[i]] < dict[s[i+1]]:
result -= dict[s[i]]
else:
result += dict[s[i]]
return result
解法 2
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = dict[s[-1]]
# 正向
for i in range(0, len(s) - 1):
if dict[s[i]] < dict[s[i+1]]:
result -= dict[s[i]]
else:
result += dict[s[i]]
return result