【问题标题】:Code to convert Roman to Integer in Python?在 Python 中将 Roman 转换为 Integer 的代码?
【发布时间】:2022-12-20 15:14:52
【问题描述】:

首先为每个罗马数字定义值并从中获取整数返回使用 while 循环将罗马定义为十进制并通过用户输入找到答案

我试过但第一次尝试没有成功,但我试过了,我得到了答案

【问题讨论】:

  • I tried but not got success in first attempt:然后发布您的尝试。

标签: python


【解决方案1】:
def value(r):
    if (r == 'I'):
        return 1
    if (r == 'V'):
        return 5
    if (r == 'X'):
        return 10
    if (r == 'L'):
        return 50
    if (r == 'C'):
        return 100
    if (r == 'D'):
        return 500
    if (r == 'M'):
        return 1000
    return -1

def romanToDecimal(str):
    res = 0
    i = 0

    while (i < len(str)):
        s1 = value(str[i])

        if (i + 1 < len(str)):

            s2 = value(str[i + 1])

            if (s1 >= s2):

                res = res + s1
                i = i + 1
            else:
                res = res + s2 - s1
                i = i + 2
        else:
            res = res + s1
            i = i + 1
    return res
print("Integer form of Roman Numeral is"),
print(romanToDecimal("MCMIV"))

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多