leetcode with python:13. Roman to Integer

题目:

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

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

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 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.

题目给我们Roman numeral的规定,再给我们字串求出该字串代表的值

整体看下来,这题最为棘手的地方在于这一段:

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.

但由于我们知道 Roman numeral 符号排列是由大到小
因此有违反的情况便是上面那些特例
于是我们做个条件式判断就能知道那些特例的位置
又刚好特例们的值=后-前
将其计算后再加到我们要return的值上即可

class Solution:    def romanToInt(self, s: str) -> int:        d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}        x=0        i=0        while i<len(s):            if i+1<len(s):                if d[s[i]]<d[s[i+1]]:                    x=x+d[s[i+1]]-d[s[i]]                    i=i+2                else:                    x=x+d[s[i]]                    i=i+1            else:                x=x+d[s[i]]                i=i+1        return x

注意:特例是两字一组因此i+2,且要再加条件判断避免i+1 out of range
最后执行时间48ms(faster than 91.86%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章