Python solution


  • 0
    R
    class Solution(object):
      def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        sym = {1:'I', 5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M'}
        # start from high digits        
        res = ''
        div = 1000
        f = False
        while num > 0:
            d = num / div
            # 9 should be IX, not VIV
            if f and d:
                if num / (div/5) == 9:
                    f, div = False, div / 5
                    continue
            
            if d == 4:
                res += sym[div]
                res += sym[div*5]
            elif d == 9:
                res += sym[div]
                res += sym[div * 10]
            else:
                res += d * sym[div]
                
            num -= d * div
            if not f:
                f, div = True, div / 2
            else:
                f, div = False, div / 5
        return res

Log in to reply
 

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