Question:
简单来说就是要求把罗马数字转为阿拉伯数字。
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
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: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Code:
class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ dict = { "I" :1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} list_roman = list(s) list_int = [] for i in list_roman: list_int.append(dict[i]) #把罗马数字转为阿拉伯数字int length = len(list_int) total = 0 i = 0 # 做一个循环,用前面一个数字比较后面一个数字,如果前面的小,那么说明需要用后面一个减前面那个数, # 再加入总数。如果前面比后面大,则继续加入总数。直到所有数字轮询完。 while i < length: if i + 1 < length: if list_int[i] < list_int[i + 1]: total = total + list_int[i+1]-list_int[i] i += 2 #这个时候i和i+1这两个数都已经被加入总和了。直接跳2个数字 continue elif list_int[i] >= list_int[i + 1]: total = total + list_int[i] elif i == length -1 : total = total + list_int[i] #如果经历完前面的,还有最后一个数,那最后一个数不需要比,直接加入总和。 else: break i += 1 return total s = Solution() print(s.romanToInt("IX")) print(s.romanToInt("MCMXCIV")) print(s.romanToInt("III")) print(s.romanToInt("IV")) print(s.romanToInt("LVIII"))
Result:
9
1994
3
4
58
解答:
通过字典的方式,把罗马数字字符串传进去后转为一位一位的int。
做一个循环,用前面一个数字比较后面一个数字,如果前面的小,那么说明需要用后面一个减前面那个数,
再加入总数。如果前面比后面大,则继续加入总数。直到所有数字轮询完。
代码中有详细解释。