给定一个整数,将其转换为对应的罗马数字表示法
转换规则:太长了,略
例:
输入: 3,4,9,58
返回:"III" "IV" "IX" "LVIII"
解法: (简单,比较容易理解)
class Solution:
def intToRoman(self, num: int) -> str:
roman = {1000:'M', 500:'D', 100:'C', 50:'L', 10:'X', 5:'V', 1:'I'}
N = 0 #用来记录要转换的数的位数
t = num
while t:
N += 1
t = t // 10
result = ''
while num:
if num >= 9 * pow(10, N - 1):
result += roman[pow(10, N - 1)] + roman[pow(10, N)]
num -= 9 * pow(10, N - 1)
elif num >= 5 * pow(10, N - 1):
result += roman[5 * pow(10, N - 1)]
num -= 5 * pow(10, N - 1)
elif num >= 4 * pow(10, N - 1):
result += roman[pow(10, N - 1)] + roman[5 * pow(10, N - 1)]
num -= 4 * pow(10, N - 1)
else:
bit, num = divmod(num , pow(10, N - 1))
result += bit * roman[pow(10, N - 1)]
N -= 1
return result
解法2:(简洁明了)
class Solution:
def intToRoman(self, num: int) -> str:
val = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1}
output = ''
for k, v in val.items():
if num == 0:
break
if num < v:
continue
output += k * (num // v)
num = num % v
return output