13--leetcode

羅馬數字轉整數

 

class Solution(object):
    def romanToInt(self, s):
        d = {'I':1, 'IV':4, 'V':5, 'IX':9, 'X':10, 'XL':40, 'L':50, 'XC':90, 'C':100, 'CD':400, 'D':500,'CM':900, 'M':1000}
        i=0
        n=len(s)
        x=0
        while i<n:
            if i+1<n and s[i]+s[i+1] in d:  
                x=x+d[s[i]+s[i+1]]
                i+=2
            elif s[i] in d:
                x=x+d[s[i]]
                i+=1
        return x
                
       
   
        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章