Roman Numerals Decoder 罗马字母转换 练习源码

编写一个函数,将罗马数字转化成阿拉伯数字。
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.

Example:例如

solution(‘XXI’) # should return 21

分析:所有罗马数字,如果小的数字放在大的数字前,就意味着他的值是大数减去小数,放在大数后,则意味着数值是大数和小数之和。
如:IX,I在X之前,则值为X-I,10-1=9
XI,I在X之后,则指为X+I,10+1=11

源码如下:

def solution(roman):
    roma_dic={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    sum = 0
    for a in range(len(roman)):
        sum = sum + roma_dic[roman[a]]
        if a>0 and roma_dic[roman[a]]>roma_dic[roman[a-1]]:
            sum = sum - 2*roma_dic[roman[a-1]]
    return sum
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值