Intuition

Create a map with the integer and the roman value of that integer, loop through the reversed array, treating the special cases (4 and 9)

Approach

Conver the number to a string then reverse it. Once reversed, create a base variable to store whether the digit is 1s, 10s, 100s, 1000s.

Loop through each digit (d) getting the equivalent in roman:

  • if d > 9 or d>4, return map[1*base] + map[(d+1)*base]
  • if d > 5, store map[5*base], decrease d
  • while d > 0 concat map[1*base]
  • return stored roman

Complexity

  • Time complexity: O(n)

  • Space complexity: O(n)

Code

class Solution(object):

    _map = {
           1: "I",
           5: "V",
          10: "X",
          50: "L",
         100: "C",
         500: "D",
        1000: "M"
    }
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        
        num_s = str(num)[::-1]
        
        b = 1
        roman = ""
        for c in num_s:
            n = int(c)
            roman = self.getRoman(n, b) + roman
            b *= 10
        
        return roman


    
    def getRoman(self, n, b):
        if n == 4 or n == 9:
            return self._map[1*b] + self._map[(n+1)*b]
        
        roman = ""
        if n >= 5:
            roman = self._map[5*b]
            n -= 5

        while n>0:
            roman += self._map[1*b]
            n -= 1

        return roman