【leetcode❤python】13. Roman to Integer

#-*- coding: UTF-8 -*-
#从前向后遍历罗马数字,
#如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数
###-----技术规则-----
#-------------------------------------------------------------------------------------
##1、相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
##2、小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
##3、小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
##4、正常使用时,连续的数字重复不得超过三次
##5、在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)

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

sol=Solution()
print sol.romanToInt('IV')

posted @ 2016-10-12 16:51  火金队长  阅读(113)  评论(0编辑  收藏  举报