码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #Roman To Integer#

时间:2015-04-11 19:32:28      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   python   


技术分享



只要做过之前的那个Integer To Roman, 这个就不会很难啦~ 掌握转换规律, 建个table就OK了


"""
Programmer  :   EOF
Date        :   2015.04.11
File        :   rti.py
E-mail      :   jasonleaster@gmail.com
"""

class Solution:
    # @return an integer
    def romanToInt(self, s):
        base = {"I":1,   "IV":4,   "V":5,   "IX":9 ,                 "X":10,  "XL":40,  "L":50,  "XC":90,                 "C":100, "CD":400, "D":500, "CM":900,                "M":1000}

        ret_num = 0
        length = len(s)
        i      = 0
        while i < length :
            if s[i:i+2] in base:
                ret_num += base[s[ i:i+2] ]
                i += 2
            elif s[i] in base:
                ret_num += base[s[i]]
                i += 1

        return ret_num

#----------- just for testing -----------

s = Solution()
print s.romanToInt("MCXLXC")






技术分享

LeetCode #Roman To Integer#

标签:leetcode   algorithm   python   

原文地址:http://blog.csdn.net/cinmyheart/article/details/44997855

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