1.罗马数字转换为数字
class Solution:
def romanToInt(self,s):
ROMAN = {
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
if s == "":
return 0
index = len(s)-2
sum = ROMAN[s[-1]]
while index>=0:
if ROMAN[s[index]]<ROMAN[s[index +1]]:
sum -= ROMAN[s[index]]
else:
sum +=ROMAN[s[index]]
index -=1
return sum
2.数字转换为罗马数字
class Solution:
def parse(self,digit,index):
NUMS = {
1:'I',
2:'II',
3:'III',
4:'IV',
5:'V',
6:'VI',
7:'VII',
8:'VIII',
9:'IX',
}
ROMAN = {
'I':['I','X','C','M'],
'V':['V','L','D','?'],
'X':['X','C','M','?']
}
s = NUMS[digit]
return s.replace('X',ROMAN['X'][index]).replace('I',ROMAN['I'][index]).replace('V',ROMAN['V'][index])
def intToRoman(self,num):
s = ''
index = 0
while num != 0:
digit =num % 10
if digit != 0:
s = self.parse(digit,index) + s
num = num//10
index += 1
return s