Integer to Roman
dictionary={1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:"IX",10:'X',50:'L',100:'C',500:'D',1000:'M',40:"XL",90:"XC",400:"CD",900:"CM"} #首先定义字典
result=[]
def step1(num):
#将num进行个、十、百、千位的分离
s = str(num)
length = len(s)
for i in range(length):
temp = int(s[i]) * pow(10,length-i-1)
result.append(temp)
return result
final = step1(30) #传入需要转换的数字、以30为例
string=[]
def step2(final):
#对分离出来的个、十、百、千位分别进行转换
for i in range(len(final)):
if (final[i] in dictionary.keys()):
string.append(dictionary[final[i]])
else:
temp=[]
if(final[i]%1000 == 0):
for j in range(final[i]//1000):
temp.append("M")
elif(final[i]>500 and final[i]%100==0):
temp.append("D")
for j in range(final[i]//100-5):
temp.append("C")
elif(final[i]<500 and final[i]%100==0):
for j in range(final[i]//100):
temp.append("C")
elif(final[i]>50 and final[i]%10==0):
temp.append("L")
for j in range(final[i]//10-5):
temp.append("X")
elif(final[i]<50 and final[i]%10==0):
for j in range(final[i]//10):
temp.append("X")
string.append("".join(temp))
return string
finalresult = step2(final)
#按照输出格式要求将数据打印出来
print("".join(finalresult))