leetcode 罗马数字与整数互转
leetcode 13.罗马数字转整数
class Solution(object): def romanToInt(self, s): res = 0 roman = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000) for i in range(len(s)-1): if roman.get(s[i])>=roman.get(s[i+1]): res += roman.get(s[i]) else: res -= roman.get(s[i]) res += roman.get(s[len(s)-1]) return res # 求解 s = Solution() s.romanToInt(‘LVIII‘) # return 58
leetcode 12.整数转罗马数字
class Solution(object): def intToRoman(self, num): rules = ( (‘M‘, 1000), (‘CM‘, 900), (‘D‘, 500), (‘CD‘, 400), (‘C‘, 100), (‘XC‘, 90), (‘L‘, 50), (‘XL‘, 40), (‘X‘, 10), (‘IX‘, 9), (‘V‘, 5), (‘IV‘, 4), (‘I‘, 1), ) res = [] for roman, dec in rules: res.extend([roman]*(num//dec)) num = num%dec return ‘‘.join(res) # 求解 s = Solution() s.intToRoman(1994) # return ‘MCMXCIV‘
相关推荐
txlCandy 2019-03-27
shishengsoft 2019-09-02
zhglinux 2019-06-29
zangdaiyang 2019-06-21
heysakura 2018-04-17
胖胖雕的GIS 2017-04-19
lispython 2019-02-25
学习编程 2018-03-02
PlatformThinking 2018-02-07