昨天和小翠聊天后,恍然发现:人是真他妈的贱,生活只要给你0.1%的甜,便能使你忘了那其余99.9%的苦。自己费尽心思想讨好别人的招数,在别人眼里也许就只是司空见惯的小把戏,也许是到了该要放手的时候了,感情天注定,望你安好!
13-罗马数字转整数
罗马数字包含以下七种字符: I
, V
, X
, L
,C
,D
和 M
。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II
,即为两个并列的 1。12 写做 XII
,即为 X
+ II
。 27 写做XXVII
, 即为 XX
+ V
+ II
。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII
,而是 IV
。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX
。这个特殊的规则只适用于以下六种情况:
I
可以放在V
(5) 和X
(10) 的左边,来表示 4 和 9。X
可以放在L
(50) 和C
(100) 的左边,来表示 40 和 90。C
可以放在D
(500) 和M
(1000) 的左边,来表示 400 和 900。
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
示例 1:
输入: "III"
输出: 3
示例 2:
输入: "IV"
输出: 4
示例 3:
输入: "IX"
输出: 9
示例 4:
输入: "LVIII"
输出: 58
解释: L = 50, V= 5, III = 3.
示例 5:
输入: "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.
这一题和上一题套路差不多的,反着来,考虑各种情况即可,没什么窍门。
代码如下:
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
s_to_int = 0
roman_list = list(s)
index = 1
while index < len(roman_list):
if s[index-1] == 'M':
s_to_int += 1000
index += 1
continue
if s[index-1] == 'C' and s[index] == 'D':
s_to_int += 400
index += 2
continue
if s[index-1] == 'C' and s[index] == 'M':
s_to_int += 900
index += 2
continue
if s[index-1] == 'C' and s[index] != 'D' and s[index] != 'M':
s_to_int += 100
index += 1
continue
if s[index-1] == 'D':
s_to_int += 500
index += 1
continue
if s[index-1] == 'X' and s[index] == 'L':
s_to_int += 40
index += 2
continue
if s[index-1] == 'X' and s[index] == 'C':
s_to_int += 90
index += 2
continue
if s[index-1] == 'X' and s[index] != 'L' and s[index] != 'C':
s_to_int += 10
index += 1
continue
if s[index - 1] == 'L':
s_to_int += 50
index += 1
continue
if s[index-1] == 'I' and s[index] == 'V':
s_to_int += 4
index += 2
continue
if s[index-1] == 'I' and s[index] == 'X':
s_to_int += 9
index += 2
continue
if s[index-1] == 'I' and s[index] != 'V' and s[index] != 'X':
s_to_int += 1
index += 1
continue
if s[index - 1] == 'V':
s_to_int += 5
index += 1
continue
else:
s_to_int = 0
if index == len(roman_list):
if roman_list[-1] == 'I':
s_to_int += 1
if roman_list[-1] == 'V':
s_to_int += 5
if roman_list[-1] == 'X':
s_to_int += 10
if roman_list[-1] == 'L':
s_to_int += 50
if roman_list[-1] == 'C':
s_to_int += 100
if roman_list[-1] == 'D':
s_to_int += 500
if roman_list[-1] == 'M':
s_to_int += 1000
return s_to_int
执行效率一般般