12. Integer to Roman

12. Integer to Roman
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
res = ''
roman = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
number = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
for i in range(len(roman)):
while num >= number[i]:
res = res + roman[i]
num -= number[i]
return res
13. Roman to Integer

13. Roman to Integer
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res = 0
for i in range(len(s)):
if i < len(s) - 1 and dic[s[i]] < dic[s[i+1]]:
res -= dic[s[i]]
else:
res += dic[s[i]]
return res
网友评论