您的位置:首页 > 其它

leetcode_13. Roman to Integer 罗马数字转化为阿拉伯数字

2016-10-19 14:18 309 查看
题目:

Given a roman numeral, convert it to an integer.

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

题意:

给定一串罗马数字,转化为阿拉伯数字

代码:

class Solution(object):

    def romanToInt(self, s):

        """

        :type s: str

        :rtype: int

        """

        

        dic = dict()

        dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

        

        result = 0

        

        for i in range(len(s)) :

            result = result + dic[s[i]]

            

            if i > 0 and dic[s[i]] > dic[s[i-1]] :

                result = result - 2*dic[s[i-1]]

        

        return result

笔记:

参考 http://www.ituring.com.cn/article/179820?utm_source=tuicool:

罗马数字转化为十进制数规则:

基本字符:   I、V、X、L、C、D、M
相应的阿拉伯数字表示为:
1、5、10、50、100、500、1000
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
(3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;

思路如下:
从左边第一个数字开始,依次加,因为有(3)的情况的存在, 加过以后判断,要是存在(3)的情况,就减去前一个(i-1)*2,因为本来应该减去前面这个小的数, 但是上次一循环还加了一次,于是这次就减去2次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: