標籤:leetcode 字串轉換
題目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
題目意思很簡單,即將一個羅馬數位字串,轉化為整數。
首先我們需要對羅馬數字有一個基本的認識,由於題目已將數字大小限定在1~3999,所以我們只需考慮千位元即可,無需涉及數位分段等複雜的問題。
下面簡要列出羅馬數字中的單位:‘I‘ 1; ‘V‘ 5; ‘X‘ 10; ‘L‘ 50 ; ‘C‘ 100; ‘D‘ 500; ‘M‘ 1000
羅馬數位大小即是將其中所包含字元所代表的的數字求和,其中數位組合規律為: I X C 會因位置的不同而加減其值。舉個栗子,IV的值為4,而VI的值為6;CD的值為400,而DC的值為600。V L D M在1~3999的範圍內則不存在該問題。
最終選擇了一個只需遍曆一次字串的方法,即從末尾開始遍曆羅馬數字字串,若出現 I(X ,C) ,如果已遍曆部分的值高於V(L, D),則在已有結果中減去I(X ,C)的值,反之,則加上。
總結一句,此題的關鍵在於找規律,最後上代碼咯~
class Solution: # @return an integer def romanToInt(self, s): L=len(s) res=0 for i in range(L-1,-1,-1): a=s[i] if a=='I': if res>=5: res-=1 else: res+=1 elif a=='V': res+=5 elif a=='X': if res>=50: res-=10 else: res+=10 elif a=='L': res+=50 elif a=='C': if res>=500: res-=100 else: res+=100 elif a=='D': res+=500 elif a=='M': res+=1000 return res
Leetcode_num14_Roman to Integer