Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
store the roman and values in arrays and iterate array to get the value. takes O(1) space and O(n) time
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
result = ''
for index in range(len(values)):
while num >= values[index]:
result += roman[index]
num -= values[index]
return result

本文介绍了一种使用Python实现的算法,该算法可以将整数转换为罗马数字。通过定义两个数组来存储数值和对应的罗马字符,算法遍历数值数组并根据整数的值拼接相应的罗马字符。
3069

被折叠的 条评论
为什么被折叠?



