您的位置:首页 > 编程语言 > Python开发

13. Roman to Integer Leetcode Python

2015-01-30 09:28 387 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

这题的做法和前面一体interger to roman 类似 建一个dictionary 去查询。 

1.先把string 反转

2. 用一个last去保存上一次的digit 

3.如果上次的digit 大于现在的digit 就将值减去两倍的digit 否则 相加。 

例如iv 反转过来是VI  直接加之后等于6 实际值为4 需要减去两倍的1 

代码如下class Solution:
# @return an integer
def romanToInt(self, s):
dict={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
last=None
sum=0
s=s[::-1]
for elem in s:
if last and dict[last]>dict[elem]:
sum-=2*dict[elem]
sum+=dict[elem]
last=elem
return sum

引用 http://www.cnblogs.com/zuoyuan/p/3779688.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息