Converting Roman Numerals to integers in python

前端 未结 17 1648
挽巷
挽巷 2020-12-03 03:56

This is now my current code after what user2486 said.

def romanMap():
    map=((\"M\",  1000),(\"CM\", 900),(\"D\",  500),(\"CD\", 400),(\"C\",  100),(\"XC\"         


        
17条回答
  •  佛祖请我去吃肉
    2020-12-03 04:27

    I know this is an old post, but I would like to add 3 solutions to convert roman numerals to numbers.

    Solution 1: (Approx Runtime = 52ms)

    def romanToInt(self, s: str) -> int:
    
         roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 }    
         num = 0
    
         for i in range(len(s)):
    
            if i!= len(s)-1 and roman[s[i]] < roman[s[i+1]]:
                 num += roman[s[i]]*-1
            else:
                 num += roman[s[i]]
    
          return num
    

    Solution 2: (Approx Runtime = 60ms)

    def romanToInt(self, s: str) -> int:
    
         roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 }    
         num = 0
    
         s = s.replace("IV", "IIII").replace("IX", "VIIII")
         s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
         s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
    
         for x in s:
            num += roman[x]
    
         return num
    

    Solution 3: (Approx Runtime = 48ms)

    def romanToInt(self, s: str) -> int:
    
         roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 }    
         num = 0
    
         for i in range(len(s)-1):
            if roman[s[i]] < roman[s[i+1]]:
                num += roman[s[i]]*-1
                continue
    
             num += roman[s[i]]
    
          num +=roman[s[-1]]
    
          return num
    

    The simplest solution appears to be the best at times :)

提交回复
热议问题