12. Integer to Roman
和之前一题反过来的题目,num范围是1-3999,于是思路也反过来就好:
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
roman = [
['X', 'V', 'I'],
['C', 'L', 'X'],
['M', 'D', 'C'],
['M', 'M', 'M']]
result = ''
count = 0
while num:
i = num % 10
num = num // 10
if i == 9:
result = roman[count][2] + roman[count][0] + result
i = 0
elif i == 4:
result = roman[count][2] + roman[count][1] + result
i = 0
elif i >= 5:
i -= 5
while i:
result = roman[count][2] + result
i -= 1
result = roman[count][1] + result
else:
while i:
result = roman[count][2] + result
i -= 1
count += 1
return result