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

LeetCode 13 Roman to Integer 解题报告

时间:2019-04-13 10:44:01      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:eth   sed   直接   分析   elf   tco   return   题目   example   

题目要求

Roman numerals are represented by seven different symbols: IVXLCDand M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one‘s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

题目分析及思路

给一个罗马数字,要求得到它对应的整数。罗马数字与整数的对应关系是:‘I‘:1, ‘V‘:5, ‘X‘:10, ‘L‘:50, ‘C‘:100, ‘D‘:500, ‘M‘:1000。罗马数字从左到右依次减小。需要考虑三种特殊情况:1)IV:4,IX:9;2)XL:40,XC:90;3)CD:400,CM:900。可以建一个字典存储这些罗马数字,之后可获得给定罗马数字各位所对应的整数列表,然后遍历这个列表,若右边的数字大于左边的数字,则需要加上右边的数字再减去两倍左边的数字;否则直接加上右边的数字。

python代码

class Solution:

    def romanToInt(self, s: str) -> int:

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

        l = [d[i] for i in s]

        ans = l[0]

        for idx in range(1,len(l)):

            if l[idx]>l[idx-1]:

                ans += (l[idx]-2*l[idx-1])

            else:

                ans += l[idx]

        return ans

            

            

        

 

LeetCode 13 Roman to Integer 解题报告

标签:eth   sed   直接   分析   elf   tco   return   题目   example   

原文地址:https://www.cnblogs.com/yao1996/p/10699853.html

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