LeetCode Easy: 13. Roman to Integer
一、题目
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
二、思路解析
罗马数规则如下:

将数字和字符串对应,当然需要用到字典,循环遍历给定的字符串中的字符,如果当前字符所对应的字典值比下一个字符所对应的字典值大,那么就执行加的操作,反之则减。这里有个小trick,由于鄙人python并不精通,不知道怎么同时访问字符串中的当前字符和当前字符的下一个字符,所以可以借用变量sums,初始化为0,然后按上述规则累加累减,最后再加上最后一个字符的字典值即可。
三、代码
#coding:utf-8
def romanToInt(s):
"""
:type s: str
:rtype: int
"""
charToInt = {"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000}
sums = 0
for item in range(len(s)-1):
if charToInt[s[item]]>=charToInt[s[item+1]]:
sums += charToInt[s[item]]
else:
sums = sums - charToInt[s[item]]
print(sums+charToInt[s[-1]])
return sums+charToInt[s[-1]]
if __name__ == '__main__':
romanToInt("DCXIX")
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号