题目
我的答案(比较弱智2333)
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
table = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
number = 0
if len(s) <= 1:
return table[s]
for index, char in enumerate(s):
number += table[char]
if index != len(s)-1:
if char == 'I':
if s[index+1] == 'V' or s[index+1] == 'X':
number -= 2
if char == 'X':
if s[index+1] == 'L' or s[index+1] == 'C':
number -= 20
if char == 'C':
if s[index+1] == 'D' or s[index+1] == 'M':
number -= 200
return number
重点
思考
看的别人的解法,主要思路:
大的在小的左边,则加
大的在小的右边,则减
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
table = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
number = 0
if len(s) <= 1:
return table[s]
for index in range(0, len(s)-1):
current_num = table[s[index]]
next_num = table[s[index+1]]
if current_num >= next_num:
number += current_num
else:
number -= current_num
number += table[s[-1]]
return number
其它解法:
- 把所有两个字符组成的罗马字代表的大小也列出来
- 把两个字符组成的罗马字都替换成单个的其他字符