top of page
Writer's pictureKarl 曹

Indirect Solution for the Roman number to integers

This is a solution for one of the leetcode problems


Intuition

For each time the combination of IV appears, for example, if we add up I and V we have 6, for convenience if we make IV valued as -2, then we can make s as a list buy list(), and iterate over it, add up all individual Roamn numbers. Then we try to find the appeared cases of combinations like IV, IX, and give -2 to them, and add them to the total sum.


Approach

  1. create dicts for individual Roman numbers and combinations

  2. iterate over them to find appeared individual numbers and combinations

  3. add them up

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        dicsub = {"IV":-2,"IX":-2,"XL":-20,"XC":-20,"CD":-200,"CM":-200}
        self.s = s
        keys = dic.keys()
        keyssub = dicsub.keys()
        identsub = []
        for i in keyssub:
            bo = i in s
            if bo:
                identsub.append(dicsub[i])
            else: 
                identsub.append(0)
        slist = list(self.s)
        ident = 0
        for i in slist:
            ident = ident + dic[i]
        sumsub = sum(identsub)
        res = sumsub + ident
        return res
Test 1:
Input: s = "LVIII"
Output: 58
Test 2:
Input: s = "MCMXCIV"
Output: 1994
Test 3 and test code: 
s = "XLIV"
a = Solution()
b=a.romanToInt(s=s)
print(b)


6 views0 comments

Recent Posts

See All

Comentários


bottom of page