Python solution


  • 0
    H
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            ans=''
            ans+='M'*(num//1000)
            num%=1000
            if num>=900:
                ans+='CM'
            elif num>=500:
                ans+='D'+'C'*(num//100-5)
            elif num>=400:
                ans+='CD'
            else:
                ans+='C'*(num//100)
            num%=100
            if num>=90:
                ans+='XC'
            elif num>=50:
                ans+='L'+'X'*(num//10-5)
            elif num>=40:
                ans+='XL'
            else:
                ans+='X'*(num//10)
            num%=10
            if num==9:
                ans+='IX'
            else:
                if num>=5:
                    ans+='V'
                    num-=5
                ans+='IV' if num==4 else 'I'*num
            return ans

Log in to reply
 

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