a013: 罗马数字
这篇教学会示范 ZeroJudge 基础题库“a013: 罗马数字”的解题过程。
题目需求
题目会提供两个正整数的“罗马数字”,需要计算这两个数字相减的“绝对值”,再转换成罗马数字输出。
题目链接:a013: 罗马数字
解答
参考“罗马数字转换”教学文章,分别将“罗马数字转阿拉伯数字”和“阿拉伯数字转罗马数字”的程序,定义为两个函数。
table = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
# 羅馬數字轉阿拉伯數字
def roman_int(n):
roman = [i for i in n]
r = roman[::-1]
output = table[r[0]]
for i in range(1, len(r)):
if table[r[i]] < table[r[i-1]]:
output = output - table[r[i]]
else:
output = output + table[r[i]]
return output
num_table = [[1000,'M'],[900,'CM'],[500,'D'],[400,'CD'],[100,'C'],[90,'XC'],[50,'L'],[40,'XL'],[10,'X'],[9,'IX'],[5,'V'],[4,'IV'],[1,'I']]
# 阿拉伯數字轉羅馬數字
def int_roman(n):
num = int(n)
output = ''
for i in num_table:
a = divmod(num, i[0])
if a!=0:
num = a[1]
output = output + i[1]*a[0]
return output
函数定义后,就可以将输入的文字转换成罗马数字,接着计算相减的绝对值,如果结果等于 0 就输出 ZERO,如果不等于 0 就再转换成罗马数字输出。
参考:绝对值 abs
while True:
try:
val = input().split(' ')
a = roman_int(val[0])
b = roman_int(val[1])
c = abs(a-b) # 計算相減的絕對值
if c==0:
print('ZERO') # 如果等於 0,輸出 ZERO
else:
print(int_roman(c)) # 如果不等於 0,轉換成羅馬數字
except:
break
微信扫码关注
抖音扫码关注