Question
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Show Tags
Show Similar Problems
Solution
Get idea from here.
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
if num<1 or num>3999:
return ''
digit = 1000
digits = []
while digit>0:
digits.append(num/digit)
num %= digit
digit /= 10
res = []
res.append( self.convert(digits[0],'M','','') )
res.append( self.convert(digits[1],'C','D','M') )
res.append( self.convert(digits[2],'X','L','C') )
res.append( self.convert(digits[3],'I','V','X') )
res = ''.join(res)
return res
def convert(self, digit, one, five, ten):
res = []
if digit==9:
res.append(one)
res.append(ten)
elif digit>=5:
res.append(five)
for ind in range(5,digit):
res.append(one)
elif digit==4:
res.append(one)
res.append(five)
elif digit>=1:
for ind in range(digit):
res.append(one)
res = ''.join(res)
return res