编写一个函数,将罗马数字转化成阿拉伯数字。
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