Greedy Algorithm (Python)


  • 0
    R
    class Solution(object):
        def intToRoman(self, num):
            self.ret = ''
            self.num = num
            
            pairs = [
                (1000, 'M'),
                (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),
                (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'),
                (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
            ]
            for p in pairs:
                self.reduce(*p)
            return self.ret
        
        def reduce(self, value, roman):
            while self.num >= value:
                self.num -= value
                self.ret += roman
    

Log in to reply
 

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