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, 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 asXXVII
, 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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(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.
题目目的是要不罗马数字转化为阿拉伯整数,其中给了6种特殊的表示格式,用较小数字放在较大数字的左边来表示另外的数字。
自己看到这个题的第一个想法就是利用字符串的查找方法来找出其中的这六种特殊表示,然后再用字典把值对应相加起来,而没有去发现数据表示的特点,所以又写了一段又臭又长的代码。。
class Solution:
def romanToInt(self, s: str) -> int:
mapdict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40, 'XC':90, 'CD':400,'CM':900}
special = ['IV','IX','XL','XC','CD','CM']
index = [ s.find(element) for element in special]
value = [mapdict[special[i]] for i in range(len(index)) if index[i]>=0]
sumvalue = sum(value)
temp = [i for i in s]
for i,element in enumerate(temp):
if i in index:
temp[i] = 'non'
temp[i+1] = 'non'
if temp[i] in mapdict:
sumvalue = sumvalue + mapdict[temp[i]]
return sumvalue
相当于是把特殊的字符都找出来,然后把特殊的字符从原来的字符串中剔除掉,剩下的都是单个字符表示的数字了,直接进行了相加即可。在写这个代码时遇到的一个问题是type error :unhash list,因为为了把特殊的字符去掉,开始把它换成的是[],但是换成了其他字符‘non’之后就没有报错了,所以[]还是不能够瞎用。
看了一下别人的代码,是抓住了字符串本身的特性,只要当前的字符串和下一个字符串比较即可,若小于下一个字符,则减去当前这个字符,若是大于或者等于了,加上当前这个字符,而对于最后一个字符而言,没有下一个字符,只需要相加即可。
class Solution:
def romanToInt(self, s: str) -> int:
dic = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
value = 0
for i, char in enumerate(s[:-1]):
if dic[char] >= dic[s[i+1]]:
value += dic[char]
else:
value -= dic[char]
value += dic[s[-1]]
return value
这个代码段的时间效率和空间占用率都比我低,刷题的时候得多注意注意题目和内部的构造,让能够事半功倍,也要学会如何去思考一个问题。