罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
- I 1
- V 5
- X 10
- L 50
- C 100
- D 500
- M 1000
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
num=0
i=0
while i<len(s)-1:
if d[s[i]]<d[s[i+1]]:
num-=d[s[i]]
else:
num+=d[s[i]]
i+=1
num+=d[s[i]]
return num
执行用时: 168 ms, 在Roman to Integer的Python3提交中击败了80.50% 的用户
给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
lm=''
if 1<=num<=3999:
#千位
qian=num//1000
lm+='M'*qian
#百位
bai=num%1000//100
if bai==9:
lm+='CM'
if 5<=bai<9:
lm+='D'
bai-=5
lm+='C'*bai
elif bai<5:
if bai==4:
lm+='CD'
elif bai<4:
lm+='C'*bai
#十位
shi=num%100//10
if shi==9:
lm+='XC'
if 5<=shi<9:
lm+='L'
shi-=5
lm+='X'*shi
elif shi<5:
if shi==4:
lm+='XL'
elif shi<4:
lm+='X'*shi
#个位
ge=num%10
if ge==9:
lm+='IX'
if 5<=ge<9:
lm+='V'
ge-=5
lm+='I'*ge
elif ge<5:
if ge==4:
lm+='IV'
elif ge<4:
lm+='I'*ge
else:
return
return lm
#只要把一个位的原理搞明白,其他的位是一样的
执行用时: 84 ms, 在Integer to Roman的Python提交中击败了86.57% 的用户