题目来源:

https://leetcode.com/problems/roman-to-integer/


题意分析:

这道题目和上一题目相反,是将罗马数字转化成阿拉伯数字。


题目思路:

只要知道罗马数字和阿拉伯数字之间是怎么转换的就可以了。先做一个字符和数值对应的字典,{'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};如果发现输入的字符串后一位比前一位小,则是出现4,9之类的,那么将前一个字符对应的数值减去两次就可以了。


代码(python):

 class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
ans = 0
size = len(s)
i = 0
while i < size:
if i > 0 and d[s[i]] > d[s[i - 1]]:
ans += d[s[i]] - 2 * d[s[i - 1]]
else:
ans += d[s[i]]
i += 1
return ans

转载请注明出处:http://www.cnblogs.com/chruny/p/4817835.html

04-13 18:17
查看更多