python实现“罗马数字转整数”的两种方法 您所在的位置:网站首页 python数字换位 python实现“罗马数字转整数”的两种方法

python实现“罗马数字转整数”的两种方法

2023-07-31 16:43| 来源: 网络整理| 查看: 265

罗马数字由7个符号表示:I, V, X, L, C, D 和 M

Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000

例如罗马数字II指两个1相加。12表示为XII,就是X+II。27为XXVII,是XX+V+II。

罗马数字排列格式为从左到右、从大到小。但是,4不是表示为IIII。相反,它表示为IV。因为如果存在小的罗马数字在大的之前,我们就需要用大的减去小的,这里就是5-1。9也是一样的规律,表示为IX。

Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: C = 100, L = 50, XXX = 30 and III = 3. Example 5: Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 1:正常思路暴力破解。先将罗马数字单独一个一个转换成数字列表。然后遍历,选判断是否为最后一个数字,如果是最后一个数字就直接加上该值。如果不是最后一个,再判断左右大小,如果左小就减去该值,其余均加。 def romanToInt(self, s): """ :type s: str :rtype: int """ result = 0 temp_list = [] for i in s: if i == 'I': temp_list.append(1) elif i == 'V': temp_list.append(5) elif i == 'X': temp_list.append(10) elif i == 'L': temp_list.append(50) elif i == 'C': temp_list.append(100) elif i == 'D': temp_list.append(500) elif i == 'M': temp_list.append(1000) for j in range(len(temp_list)): if j == len(temp_list)-1: result += temp_list[j] else: if temp_list[j]


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有