Python Iterative Solution (easy to understand)


  • 0
    K
    class Solution(object):
        
        def getFirst(self, num, integers):
            
            # go through the list of integers
            for i in range(len(integers)):
                
                # find the integer that is greatest less than number
                if integers[i] > num:
                    return i - 1
                    
            # get the max 
            return len(integers) - 1
            
        def intToRoman(self, num):
            
            # arrays correspond to each other by index
            romanNumerals = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"]
            integers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
            
            # string holder
            res = ""
            
            # get the greatest less than number
            first = self.getFirst(num, integers)
            
            while num > 0:
    
                # we need the greatest less than num
                if num < integers[first]:
                    # go left on the array to find the less integer
                    first -= 1
                
                # add to the res and subtract by using the arrays 
                else:
                    res += romanNumerals[first]
                    num -= integers[first]
                
            return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.