码迷,mamicode.com
首页 > 编程语言 > 详细

13. Roman to Integer Leetcode Python

时间:2015-01-30 10:53:17      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   array   hashtable   

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

13. Roman to Integer Leetcode Python

标签:leetcode   python   array   hashtable   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/43302861

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!