罗马数字转整数
解题思路
首先将字符串s转换为list,并初始化Int为0,用来记录罗马数字的大小。初始化flag为空字符串,用来标记本次while循环之前的上一次循环是哪个罗马数字。每次循环之后,弹出最后一个字符,这样list长度就-1
在while循环中,不同的字符对应不同的增加量,如果碰到’I’、‘X’、‘C’,可能需要根据flag的值进行回退,代码见下:
class Solution:
def romanToInt(self, s: str) -> int:
str_list = list(s)
Int = 0
flag = ''
while (len(str_list) > 0):
if (str_list[len(str_list)-1] == 'I'):
if (flag == "V"):
Int = Int - 5 + 4 #回退
elif(flag == "X"):
Int = Int - 10 + 9 #回退
else:
Int = Int + 1
flag = "I"
if (str_list[len(str_list)-1] == 'V'):
Int = Int + 5
flag = "V"
if (str_list[len(str_list)-1] == 'X'):
if (flag == "L"):
Int = Int - 50 + 40 #回退
elif(flag == "C"):
Int = Int - 100 + 90 #回退
else:
Int = Int + 10
flag = "X"
if (str_list[len(str_list)-1] == 'L'):
Int = Int + 50
flag = "L"
if (str_list[len(str_list)-1] == 'C'):
if (flag == "D"):
Int = Int - 500 + 400 #回退
elif(flag == "M"):
Int = Int - 1000 + 900 #回退
else:
Int = Int + 100
flag = "C"
if (str_list[len(str_list)-1] == 'D'):
Int = Int + 500
flag = "D"
if (str_list[len(str_list)-1] == 'M'):
Int = Int + 1000
flag = "M"
str_list.pop()
return Int
leetcode的思路
class Solution:
SYMBOL_VALUES = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
def romanToInt(self, s: str) -> int:
ans = 0
n = len(s)
for i, ch in enumerate(s):
value = Solution.SYMBOL_VALUES[ch]
if i < n - 1 and value < Solution.SYMBOL_VALUES[s[i + 1]]:
ans -= value
else:
ans += value
return ans