练习题——阿拉伯数字转化为罗马数字

题目

罗马数字来源于古罗马编码系统。它们是基于字母表的特定字母的组合,所表示的数等于这些数字相加(或者是相减)得到的数。前十位的罗马数字是:
I,II,III,IV,V,VI,VII,VIII,IX和X。
罗马记数系统不是直接的十进制为基础,它没有零。罗马数字是根据这七个符号的组合:
符号值
1 (unus)
5 (quinque)
10 (decem)
50 (quinquaginta)
100 (centum)
500 (quingenti)
1,000 (mille)
更多额外的关于罗马数字的信息可以参考维基百科的文章.
在这个任务里,你应该返回给出指定的整数值的范围从13999的罗马数字。
输入: 一个整数 (int).
输出: 一个字符串形式的罗马数字 (str).
前提: 0 < number < 4000

测试数据

6
76
499
3888

目标结果

VI
LXXVI
CDXCIX
MMMDCCCLXXXVIII

解题思路

将数字从大到小拆分,需把握规律,依次将结果保存到列表中,最后打印出来。

脚本1

def checkio(num):
    roman = [['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
             ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
             ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
             ['', 'M', 'MM', 'MMM']]
    result = []
    result.append(roman[3][ num / 1000 % 10 ])
    result.append(roman[2][ num / 100 % 10 ])
    result.append(roman[1][ num / 10 % 10 ])
    result.append(roman[0][ num % 10 ])
    return ''.join(result)

text = '''6
76
499
3888'''

for line in text.split('
'):
    print checkio(int(line))

脚本2

def operate(data, divisor, str1, str2, str3):
    result = ''
    temp = data // divisor
    if temp:
        if temp >= 5:
            if temp == 9:
                result = str1 + str3
                temp -= 9
            else:
                result = str2
                temp -= 5
        if temp:
            if temp == 4:
                result += str1 + str2
            else:
                result += str1 * temp
        return result
 
def checkio(data):
    result = []
    temp = data // 1000
    if temp:
        result.append('M' * temp)
        data %= 1000
    temp = operate(data, 100, 'C', 'D', 'M')
    if temp:
        result.append(temp)
        data %= 100
    temp = operate(data, 10, 'X', 'L', 'C')
    if temp:
        result.append(temp)
        data %= 10
    temp = operate(data, 1, 'I', 'V', 'X')
    if temp:
        result.append(temp)
    return ''.join(result)

text = '''6
76
499
3888'''

for line in text.split('
'):
    print checkio(int(line))

如果您觉得我的文章对您有帮助并想鼓励我继续原创,请扫描下方二维码进行打赏!

谢谢!

原文地址:https://www.cnblogs.com/yestreenstars/p/5485178.html